log4net 是dotnet平台下的一个日记记录组件。
一 NuGet中安装log4net包:
二 配置log4net.config文件
配置文件内容:
三 配置 XmlConfigurator
有多种方法,这里因为是在web项目下,所以我放在Global.asax文件中
void Application_Start(object sender, EventArgs e) {// 在应用程序启动时运行的代码log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));}
四 使用
public partial class web_Pay : BasePage
{static readonly ILog log = LogHelper.GetLogger(typeof(web_Pay));protected void Page_Load(object sender, EventArgs e){log.Error("error");log.Info("info");}
}
在这里我对 ILog进行了一层封装
public interface ILog{void Debug(object message);void Debug(object message, Exception exception);void Error(object message);void Error(object message, Exception exception);void Fatal(object message);void Fatal(object message, Exception exception);void Info(object message);void Info(object message, Exception exception);void Warn(object message);void Warn(object message, Exception exception);} public sealed class LogWrapper : ILog{private readonly log4net.ILog _logger;internal LogWrapper(Type type){_logger = log4net.LogManager.GetLogger(type);}public void Debug(object message){_logger.Debug(message);}public void Debug(object message, Exception exception){_logger.Debug(message, exception);}public void Error(object message){_logger.Error(message);}public void Error(object message, Exception exception){_logger.Error(message, exception);}public void Fatal(object message){_logger.Fatal(message);}public void Fatal(object message, Exception exception){_logger.Fatal(message, exception);}public void Info(object message){_logger.Info(message);}public void Info(object message, Exception exception){_logger.Info(message, exception);}public void Warn(object message){_logger.Warn(message);}public void Warn(object message, Exception exception){_logger.Warn(message, exception);}}public static class LogHelper{public static ILog GetLogger(Type type){return new LogWrapper(type);}}