博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
.net core log4net
阅读量:6922 次
发布时间:2019-06-27

本文共 3280 字,大约阅读时间需要 10 分钟。

 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/

 

转载于:https://www.cnblogs.com/drivenwinder/p/8300881.html

你可能感兴趣的文章
bootstrap大图轮播手机端不能手指滑动解决办法
查看>>
DNS服务器*****(二)
查看>>
tomcat在conf/Catalina/localhost目录下配置项目路径
查看>>
网络设备在网络环境中的应用
查看>>
ICN:SDN后的下一个热潮
查看>>
图解linux下top命令的使用
查看>>
Linux远程管理工具screen
查看>>
利用Server2008影卷复制功能快速恢复误删文件
查看>>
Android学习—动态布局方法总结
查看>>
需求与暗需求
查看>>
那些好用的小工具——Database Browser
查看>>
如何使用Rebase以及bind来重定位和绑定dll
查看>>
Diff程序的原理
查看>>
测试粒度
查看>>
oral_quiz->#俩queue实现stack#
查看>>
Hibernate 多对一关联配置
查看>>
解决ios safari中按钮圆角问题
查看>>
理解 Java 的 GC 与 引用
查看>>
常用LINUX_C字符串处理函数整理
查看>>
URL 和 URI 区别?
查看>>