【发布时间】:2010-09-22 15:30:11
【问题描述】:
我一直在寻找一种方法来记录类名和方法名作为我的日志基础设施的一部分。显然,我想让它在运行时易于使用和快速。我已经阅读了大量有关记录类名和方法名的内容,但我遇到了 2 个主题。
- log4net 使用内部抛出异常来生成堆栈帧,如果您通常将其用于所有日志记录,则会变得昂贵。
- 混乱。那里有很多文学作品。我已经尝试了很多,但没有得到有用的东西。
如果你逗我一会儿,我想重新设置。
我在我的项目中创建了一个这样的类
public static class Log {
private static Dictionary<Type, ILog> _loggers = new Dictionary<Type, ILog>();
private static bool _logInitialized = false;
private static object _lock = new object();
public static string SerializeException(Exception e) {
return SerializeException(e, string.Empty);
}
private static string SerializeException(Exception e, string exceptionMessage) {
if (e == null) return string.Empty;
exceptionMessage = string.Format(
"{0}{1}{2}\n{3}",
exceptionMessage,
(exceptionMessage == string.Empty) ? string.Empty : "\n\n",
e.Message,
e.StackTrace);
if (e.InnerException != null)
exceptionMessage = SerializeException(e.InnerException, exceptionMessage);
return exceptionMessage;
}
private static ILog getLogger(Type source) {
lock (_lock) {
if (_loggers.ContainsKey(source)) {
return _loggers[source];
}
ILog logger = log4net.LogManager.GetLogger(source);
_loggers.Add(source, logger);
return logger;
}
}
public static void Debug(object source, object message) {
Debug(source.GetType(), message);
}
public static void Debug(Type source, object message) {
getLogger(source).Debug(message);
}
public static void Info(object source, object message) {
Info(source.GetType(), message);
}
public static void Info(Type source, object message) {
getLogger(source).Info(message);
}
...
private static void initialize() {
XmlConfigurator.Configure();
}
public static void EnsureInitialized() {
if (!_logInitialized) {
initialize();
_logInitialized = true;
}
}
}
(如果这段代码看起来很熟悉,那是因为它是从示例中借来的!)
无论如何,在我的整个项目中,我都使用这样的行来记录:
Log.Info(typeof(Program).Name, "System Start");
嗯,这样的作品。最重要的是,我得到了类名但没有方法名。更重要的是,我正在用这种“typeof”垃圾污染我的代码。如果我在文件之间复制并粘贴一段代码,等等,日志框架就会撒谎!
我尝试使用 PatternLayout (%C{1}.{M}) 但这不起作用(它所做的只是将“Log.Info”写入日志——因为一切都通过 Log. X 静态方法!)。此外,这应该很慢。
那么,考虑到我的设置和我希望简单快速的愿望,最好的方法是什么?
提前感谢任何帮助。
【问题讨论】: