.NET常用的日志组件有NLog、Log4net等,.NET CORE下微软也自带了日志组件,到目前为止还没用过,而我本人常用的是log4net,下面简单讲讲.NET CORE下怎么使用log4net记录日志。
新建一个ASP.NET CORE项目,为项目添加log4net程序包,
log4net.config文件配置如下:
1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3 <!-- This section contains the log4net configuration settings --> 4 <log4net> 5 <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> 6 <file value="Log/" /> 7 <appendToFile value="true" /> 8 <rollingStyle value="Composite" /> 9 <staticLogFileName value="false" /> 10 <datePattern value="yyyyMMdd'.log'" /> 11 <maxSizeRollBackups value="10" /> 12 <maximumFileSize value="50MB" /> 13 <layout type="log4net.Layout.PatternLayout"> 14 <conversionPattern value="%date [%thread] %-5level %message%newline" /> 15 </layout> 16 </appender> 17 18 <!-- Setup the root category, add the appenders and set the default level --> 19 <root> 20 <level value="ALL" /> 21 <appender-ref ref="RollingLogFileAppender" /> 22 </root> 23 24 </log4net> 25 </configuration>
接下来编写一个记录日志的公共类代码如下:(本人看到有些开发者将ILog对象直接返回,在调用的时候直接调用ILog对象的方法,这样会造成调用的类库中都必须引用log4net类库,很麻烦,像如下封装后调用的地方只需要引用Logger类所在类库即可)
public class Logger { private static ILog logger; static Logger() { if (logger == null) { var repository = LogManager.CreateRepository("NETCoreRepository"); //log4net从log4net.config文件中读取配置信息 XmlConfigurator.Configure(repository, new FileInfo("log4net.config")); logger = LogManager.GetLogger(repository.Name, "InfoLogger"); } } /// <summary> /// 普通日志 /// </summary> /// <param name="message"></param> /// <param name="exception"></param> public static void Info(string message, Exception exception = null) { if (exception == null) logger.Info(message); else logger.Info(message, exception); } /// <summary> /// 告警日志 /// </summary> /// <param name="message"></param> /// <param name="exception"></param> public static void Warn(string message, Exception exception = null) { if (exception == null) logger.Warn(message); else logger.Warn(message, exception); } /// <summary> /// 错误日志 /// </summary> /// <param name="message"></param> /// <param name="exception"></param> public static void Error(string message, Exception exception = null) { if (exception == null) logger.Error(message); else logger.Error(message, exception); } }
接下来就是在任意控制器或者类中使用刚编写的Logger类来记录日志到文件中
[Produces("application/json")] [Route("api/Default")] public class DefaultController : ControllerBase { public readonly IOptions<AppSettings> _Setting; public DefaultController(IOptions<AppSettings> _setting) { _Setting = _setting; } public async Task<string> GetAppsetting() { string name= _Setting.Value.Name; string age = _Setting.Value.Age; Logger.Error(age);//此处调用日志记录函数记录日志 return name + age; } }
2019-07-26 16:09:30,220 [9] INFO 18 2019-07-26 16:12:15,394 [9] ERROR 18
如果需要限制历史日志文件保存最大数量,请将<rollingStyle value="Composite" />改为:<rollingStyle value="Size" />,此时,maxSizeRollBackups配置才会生效。
<?xml version="1.0" encoding="utf-8" ?> <configuration> <!-- This section contains the log4net configuration settings --> <log4net> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="Log/" /> <appendToFile value="true" /> <rollingStyle value="Size" /> <staticLogFileName value="false" /> <datePattern value="yyyyMMdd'.log'" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="50MB" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %message%newline" /> </layout> </appender> <!-- Setup the root category, add the appenders and set the default level --> <root> <level value="ALL" /> <appender-ref ref="RollingLogFileAppender" /> </root> </log4net> </configuration>
注意,如果Logger类中抛出FileNotFoundException异常,说明目录下未找到log4net.config文件,这时请在项目log4net.config文件上右键——属性——将“复制到输出目录”项的值改为“始终复制”即可。
摘自:这里