.NET Core使用log4Net记录日志

1.引入Nuget包

log4net

2.添加log4Net配置文件

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <configuration>
 3   <!-- This section contains the log4net configuration settings -->
 4   <log4net>
 5     <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
 6       <layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" />
 7     </appender>
 8 
 9     <appender name="FileAppender" type="log4net.Appender.FileAppender">
10       <file value="log-file.log" />
11       <appendToFile value="true" />
12       <layout type="log4net.Layout.PatternLayout">
13         <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
14       </layout>
15     </appender>
16 
17     <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
18       <file value="logfile/" />   //指定日志文件保存的目录
19       <appendToFile value="true" />
20       <rollingStyle value="Composite" />
21       <staticLogFileName value="false" />
22       <datePattern value="yyyyMMdd'.log'" />
23       <maxSizeRollBackups value="10" />
24       <maximumFileSize value="1MB" />
25       <layout type="log4net.Layout.PatternLayout">
26         <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
27       </layout>
28     </appender>
29 
30     <!-- Setup the root category, add the appenders and set the default level -->
31     <root>
32       <level value="ALL" />
33       <appender-ref ref="ConsoleAppender" />
34       <appender-ref ref="FileAppender" />
35       <appender-ref ref="RollingLogFileAppender" />
36     </root>
37 
38   </log4net>
39 </configuration>

3.在StartUp.cs中配置log4Net

 1         //为StartUp.cs添加属性
 2         public static ILoggerRepository repository { get; set; }
 3 
 4         public Startup(IConfiguration configuration, IHostingEnvironment env)
 5         {
 6             Configuration = configuration;
 7             //log4net
 8             repository = LogManager.CreateRepository("NETCoreRepository");
 9             //指定配置文件
10             XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
11 
12         }

4.在程序中中使用log4Net写日志

下面是注入到控制器中的示例

 1     public class HomeController : Controller
 2     {
 3         //log4Net
 4         private ILog log;
 5         public UploadFilesController(IHostingEnvironment hostingEnv)
 6         {
 7             //log4Net
 8             this.log = LogManager.GetLogger(Startup.repository.Name, typeof(HomeController));
 9         }
10         public IActionResult Index()
11         {
12             var name = message.Name;
13             var age = message.Age;
14             log.Error("error message");
15             return View();
16         }
17 }

 

 

 

posted @ 2018-01-17 21:04 Degalo 阅读(...) 评论(...) 编辑 收藏