|
Oct
08
|
log4net的一般使用方式是这样:
private static readonly log4net.ILog log
= log4net.LogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
在每一个需要记录日志的类中都需要声明一个实例, 本来这没什么, 不过, 记录日志时, 它的方法就太繁琐了. 比如Debug方法只能接受一个参数, 如果想使用格式化输出, 要么使用DebugFormat, 要么自己拼字符串. DebugFormat比Debug多敲几个键盘, 而且不好看. 我就喜欢直接用
log.debug("a = {0}", a");
所以, 包装一个类:
/// <summary>
/// 日志记录.
/// </summary>
class Logger {
private log4net.ILog log;
public Logger() {
StackTrace st = new StackTrace(1, true);
StackFrame[] stFrames = st.GetFrames();
Type t = stFrames[0].GetMethod().DeclaringType;
log = log4net.LogManager.GetLogger(t);
}
public void debug(string format, params object[] args) {
log.DebugFormat(format, args);
}
public void info(string format, params object[] args) {
log.InfoFormat(format, args);
}
public void error(string format, params object[] args) {
log.ErrorFormat(format, args);
}
public void fatal(string format, params object[] args) {
log.FatalFormat(format, args);
}
}
在构造函数中获取使用Logger的类的类型(Type), 以便在记录日志时打印出来. 这样使用:
private static Logger log = new Logger();
log.debug("a = {0}", a");
方便多了.
Related posts:
Leave a Reply

Recent Comments