netcore中使用log4net日志
第一、控制台程序中使用log4net
static void Main(string[] args) { ILoggerRepository repository = LoggerManager.CreateRepository("NETCoreRepository"); //BasicConfigurator.Configure(repository);//仅用于控制台日志 XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));//文件日志 ILog log = LogManager.GetLogger(repository.Name, "NETCorelog4net"); log.Info("lance test"); log.Error("lance test error"); Console.WriteLine("Hello World!"); Console.Read(); }
log4net.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <!-- This section contains the log4net configuration settings --> <log4net> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" /> </appender> <appender name="FileAppender" type="log4net.Appender.FileAppender"> <file value="log-file.log" /> <appendToFile value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="log\\"/> <appendToFile value="true" /> <rollingStyle value="Composite" /> <staticLogFileName value="false" /> <datePattern value="yyyy-MM-dd'.log'"/> <maxSizeRollBackups value="10" /> <maximumFileSize value="1MB" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> <!-- Setup the root category, add the appenders and set the default level --> <root> <level value="ALL" /> <appender-ref ref="ConsoleAppender" /> <appender-ref ref="FileAppender" /> <appender-ref ref="RollingLogFileAppender" /> </root> </log4net> </configuration>
注意log4net.confg 右键设置 Copy to Output directory :copy always
第二、netcore WebApi中使用
在 StartUp.cs中增加
public static ILoggerRepository repository { get; set; } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } repository = LoggerManager.CreateRepository("NetCoreRepository"); log4net.Config.XmlConfigurator.Configure(repository, new FileInfo("log4net.config")); app.UseMvc(); }
在站点根目录下增加log4net.config ,同上面一样
在controller中的使用
private ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(ValuesController)); // GET api/values [HttpGet] public IEnumerable<string> Get() { log.Info("get value controller"); return new string[] { "value1", "value2" }; }
个人签名:天行健,君子以自强不息