在.ToolKits层添加log4net包,使用命令安装:Install-Package log4net,然后添加文件夹Helper,新建一个LoggerHelper.cs。
//LoggerHelper.cs using log4net; using log4net.Config; using log4net.Repository; using System; using System.IO; namespace Meowv.Blog.ToolKits.Helper { public static class LoggerHelper { private static readonly ILoggerRepository Repository = LogManager.CreateRepository("NETCoreRepository"); private static readonly ILog Log = LogManager.GetLogger(Repository.Name, "NETCorelog4net"); static LoggerHelper() { XmlConfigurator.Configure(Repository, new FileInfo("log4net.config")); } /// <summary> /// 写日志 /// </summary> /// <param></param> /// <param></param> public static void WriteToFile(string message) { Log.Info(message); } /// <summary> /// 写日志 /// </summary> /// <param></param> /// <param></param> public static void WriteToFile(string message, Exception ex) { if (string.IsNullOrEmpty(message)) message = ex.Message; Log.Error(message, ex); } } }在.HttpApi.Hosting中添加log4net配置文件,log4net.config配置文件如下:
//log4net.config <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net debug="false"> <appender type="log4net.Appender.RollingFileAppender,log4net"> <param value="log4net/info/" /> <param value="true" /> <param value="-1"/> <param value="5MB"/> <param value="Composite" /> <param value="yyyyMMdd\\HH".log"" /> <param value="false" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param value="%n { "system": "Meowv.Blog", "datetime": "%d", "description": "%m", "level": "%p", "info": "%exception" }" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <levelMin value="INFO" /> <levelMax value="INFO" /> </filter> </appender> <appender type="log4net.Appender.RollingFileAppender,log4net"> <param value="log4net/error/" /> <param value="true" /> <param value="-1"/> <param value="5MB"/> <param value="Composite" /> <param value="yyyyMMdd\\HH".log"" /> <param value="false" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param value="%n { "system": "Meowv.Blog", "datetime": "%d", "description": "%m", "level": "%p", "info": "%exception" }" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <levelMin value="ERROR" /> <levelMax value="ERROR" /> </filter> </appender> <root> <level value="ALL"></level> <appender-ref ref="info"/> <appender-ref ref="error"/> </root> </log4net> </configuration>此时再去调用 .../HelloWorld/Exception,将会得到日志文件,内容是以JSON格式进行存储的。
关于Filter的更多用法可以参考微软官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/controllers/filters
到这里,系统的异常处理和日志记录便完成了,你学会了吗?