-
Log4net 介绍
1、Log4net 是什么?
Log4net 是 Apache 旗下一个开源的日志框架的项目,它是Log4j 的一个复制版。Log4net中定义了多种日志信息输出模式。它可以根据需要将日志输出到控制台、文本文件、windows 日志事件查看器中、括数据库,邮件发送,以便我们可以根据日志快速定位线上系统的问题。
2、Log4net 日志等级
从高到底分别为:OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL
二、ASP.NET MVC 使用 Log4net 示例
2.1 如何安装 Log4net Log4net
-
使用Nuget 安装 Log4net(工具-NuGet包管理器-程序包管理器控制台(N))
-
使用管理NuGet程序包功能找到Log4net进行安装。
2.2 创建 log4net.config 配置文件 ,并且将该文件的属性“复制到输出目录”修改为 “始终复制。
log4net.config内容如下:
<?xml version="1.0" encoding="utf-8" ?><configuration> <configSections> <p name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <root> <level value="ALL" /> <appender-ref ref="LogFileAppender" /> <!--<appender-ref ref="EventLogAppender" />--> </root> <!--定义输出到文件--> <appender name ="LogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--定义文件存放位置--> <param name="File" value ="Logs\"/> <param name="AppendToFile" value="true" /> <param name="MaxSizeRollBackups" value="100" /> <param name="MaxFileSize" value="10240" /> <param name="StaticLogFileName" value="false" /> <!--这是按日期产生文件夹--> <datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.txt'"/> <param name="RollingStyle" value ="Date" /> <!--不以独占方式记录日志,仅在记录每个日志的最短时间内锁定,因为部署到服务器上遇到了文件被占用无法下载日志--> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <layout type="log4net.Layout.PatternLayout"> <!--定义输出格式--> <!--示例 2018-08-20 12:10:49,348 -线程ID:[21] 日志级别:[INFO ] : [日志信息]--> <!--<conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别: %-5level %n错误描述:%message%newline %n"/>--> <conversionPattern value="%n========== %n【日志级别】%-5level %n【记录时间】%date %n【线程编号】[%thread] %n【执行时间】[%r]毫秒 %n【出错文件】%F %n【出错行号】%L %n【出错的类】%logger 属性[%property{NDC}] %n【错误描述】%message %n【错误详情】%newline"/> </layout> <!--过滤级别 FATAL > ERROR > WARN > INFO > DEBUG--> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="DEBUG" /> <param name="LevelMax" value="FATAL" /> </filter> </appender> <!--定义输出到 windows 事件中--> <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"></conversionPattern> </layout> </appender> </log4net></configuration><?xml version="1.0" encoding="utf-8" ?><configuration> <configSections> <p name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections>
2.3 新建LogHelper.cs通用日志类
代码如下:
public class LogHelper { private ILog _log4Net = null; private const string DEFAULT_LOGGER_NAME = "Logger"; /// <summary> /// Prevents a default instance of the <see cref="LogWriter"/> class from being created. /// </summary> /// <param name="log4NetInstance">The log4net instance to be used.</param> private LogHelper(ILog log4NetInstance) { _log4Net = log4NetInstance; }
/// <summary> /// Gets a logger with the specified configuration name. /// </summary> /// <param name="configName">Name of the logger in the configuration.</param> /// <returns>The logger obtained.</returns> /// <exception cref="System.Configuration.ConfigurationException">Thrown when no logger with the specified configuration name was found.</exception> public static LogHelper GetLogger(string configName) { var logger = LogManager.GetLogger(configName); if (logger == null) { throw new ArgumentException(string.Format("No logger configuration named '{0}' was found in the configuration.", configName), "configName"); } return new LogHelper(logger); }
/// <summary> /// Gets the default. /// </summary> public static LogHelper Default { get { return GetLogger(DEFAULT_LOGGER_NAME); } }
/// <summary> /// Writes an information level logging message. /// </summary> /// <param name="message">The message to be written.</param> public void WriteInfo(object message) { _log4Net.Info(message); }
/// <summary> /// Writes a warning level logging message. /// </summary> /// <param name="message">The message to be written.</param> public void WriteWarning(object message) { _log4Net.Warn(message); }
/// <summary> /// Writes a warning level logging message. /// </summary> /// <param name="message">The message to be written.</param> /// <param name="exception">The exception.</param> public void WriteWarning(object message, System.Exception exception) { _log4Net.Warn(message, exception); }
/// <summary> /// Writes the error. /// </summary> /// <param name="message">The message to be written.</param> public void WriteError(object message) { _log4Net.Error(message); }
/// <summary> /// Writes the error level logging message.. /// </summary> /// <param name="message">The message to be written.</param> /// <param name="exception">The exception.</param> public void WriteError(object message, System.Exception exception) { _log4Net.Error(message, exception); }
/// <summary> /// Writes the fatal error level logging message.. /// </summary> /// <param name="message">The message to be written.</param> public void WriteFatal(object message) { _log4Net.Fatal(message); }
/// <summary> /// Writes the fatal error level logging message.. /// </summary> /// <param name="message">The message to be written.</param> /// <param name="exception">The exception.</param> public void WriteFatal(object message, System.Exception exception) { _log4Net.Fatal(message, exception); }
public void DeleteLog() { string logDirPath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Log"); if (!Directory.Exists(logDirPath)) return; int days = 30; foreach (string filePath in Directory.GetFiles(logDirPath)) { DateTime dt; DateTime.TryParse(Path.GetFileNameWithoutExtension(filePath).Replace(@"Log\", "").Replace(".", "-"), out dt); if (dt.AddDays(days).CompareTo(DateTime.Now) < 0) { File.Delete(filePath); } } } }
2.4 AssemblyInfo.cs 文件配置log4net.config
特别注意:针对为web项目要加载web项目对应的AssemblyInfo.cs文件中去,这一点很关键要不然就不能输出日志文件
[assembly: log4net.Config.XmlConfigurator(Watch = true, ConfigFileExtension = "config", ConfigFile = @"Configs\log4net.config")]
2.5 自定义日志异常处理文件:MyExceptionFileAttribute.cs
用来处理异常记录日志文件,然后可以指定错误的跳转页面。
public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); if (!string.IsNullOrWhiteSpace(filterContext.Exception.StackTrace)) { LogHelper.Default.WriteError(filterContext.Exception.StackTrace); } //页面跳转到错误页面 filterContext.HttpContext.Response.Redirect("/Error"); }
2.6 Global.asax新增Log4Net的配置信息
Application_Start.cs 方法加入下面两行代码:
// 注册log4net
log4net.Config.XmlConfigurator.Configure();
// 注册异常日志文件
GlobalFilters.Filters.Add(new MyExceptionFileAttribute());
测试用法
LoginController.cs 代码加一个异常
public ActionResult Index() { int a = 0; int b = 6 / a; return View(); }
效果展示:
结语
本文主要简单介绍ASP.NET MVC 使用 Log4net 的过程。具体的一些用法大家也可以互相交流,比如:如何错误日志如何发邮件、数据库的方式存储、日志文件异步存储等等。后续小编会继续更新相关内容和大家一起学习交流。