asp.net core配置log4net

一、asp.net core webapi添加日志

1.NuGet安装:log4net

2.Startup中加入:

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

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                //.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
            repository = LogManager.CreateRepository("NETCoreRepository");
            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
            SDKProperties.LogRepository = repository;//类库中定义的静态变量
        }

3.加入log配置文件(log4net.config)



  
  
    
      
    

    
      
      
      
        
      
    

    
      
      
      
      
      
      
      
      
        
      
    

    
    
      
      
      
      
    

  
4.写日志测试

   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            var log = LogManager.GetLogger(repository.Name, typeof(Startup));
            log.Info("test");
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();

            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "其实,我是一个演员。");
                c.ShowRequestHeaders();
            });
        }
二、webapi引用的类库添加日志

1.类库中添加类:

public class SDKProperties
    {
        public static ILoggerRepository LogRepository { get; set; }
    }
    public class Base
    {
        private static readonly ILog log = LogManager.GetLogger(SDKProperties.LogRepository.Name, typeof(Base));

        public static void LogTest()
        {
            log.Info("Info test");
            log.Warn("Warn test");
            log.Error("Error test");
        }
    }

2.webapi->Startup()中,初始化变量:

SDKProperties.LogRepository = repository;//类库中定义的静态变量
3.webapi->value控制器
   [HttpGet]
        public IEnumerable Get()
        {
            log.Info("Dying in the sun");

            Base.LogTest();
            return new string[] { "value1", "value2" };
        }
4.运行

asp.net core配置log4net_第1张图片
查看日志:

asp.net core配置log4net_第2张图片


这样webapi和类库中都能写日志了。


你可能感兴趣的:(asp.net,core)