.net core log4net

 asp.net core 虽然自带了日志,但是还是老牌Log4Net日志强大。ASP.NET Core有很好的扩展,可以把Log4net配置为类似为内置日志模块,

利用IOC,很好的在其他组件中使用

1 使用第三方组件 Microsoft.Extensions.Logging.Log4Net.AspNetCore,在nuget中搜索即可

2. 注册

public class Startup
    {
        public static ILoggerRepository repository { get; set; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            loggerFactory.AddLog4Net();
            app.UseMvc();
        }

  3. 使用

 [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        private readonly ILogger log;
        public ValuesController(ILogger<ValuesController> logger)
        {
            this.log = logger;
        }


        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            log.LogInformation("Get values using Log4net ");
            return new string[] { "value1", "value2","value3","value4" };
        }
        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            log.LogInformation("Get values by id " + id.ToString() + " using log4net");
            return "value test" +id.ToString();
        }
    }
}

 

配置文件 log4net.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="RollingFileAppender" />
    </root>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="Logs\log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="1024KB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
  </log4net>
</configuration>

放在发布的根目录下即可。

注意:Microsoft.Extensions.Logging.Log4Net.AspNetCore 默认的配置文件名为log4net.config,并且配置文件的根节点log4net,

查看源码即可看到,上面的配置文件节点是我自己修改过后的,变成 log4netConfig["configuration"]["log4net"];

Microsoft.Extensions.Logging.Log4Net.AspNetCore 部分源码:

        /// <summary>
        /// The default log4net config file name.
        /// </summary>
        private const string DefaultLog4NetConfigFile = "log4net.config";

 

        /// <summary>
        /// Parses log4net config file.
        /// </summary>
        /// <param name="filename">The filename.</param>
        /// <returns>The <see cref="XmlElement"/> with the log4net XML element.</returns>
        private static XmlElement Parselog4NetConfigFile(string filename)
        {
            using (FileStream fp = File.OpenRead(filename))
            {
                var settings = new XmlReaderSettings
                {
                    DtdProcessing = DtdProcessing.Prohibit
                };
              
                var log4netConfig = new XmlDocument();
                log4netConfig.Load(filename);
                using (var reader = XmlReader.Create(fp, settings))
                {
                    log4netConfig.Load(reader);
                }

                fp.Flush();
                fp.Dispose();

                return log4netConfig["log4net"];
            }
        }

 

 较好的做法是利用Common.logging +Log4net,还在实践中...

 在windows 7上正常,未在Linux上验证..

 参考文章:

 http://www.cnblogs.com/linezero/p/log4net.html

 https://dotnetthoughts.net/how-to-use-log4net-with-aspnetcore-for-logging/

 

posted @ 2018-01-17 08:46  Drivenwinder  阅读(527)  评论(0编辑  收藏  举报