在微软发布的ASP.NET Core 中给了一种默认的日志配置选择,那么当我们使用其他的日志中间件是如何配置呢?如下:
1、使用NutGet 获取日志库:Microsoft.Extensions.Logging.Log4Net.AspNetCore 和 Log4Net库
2、配置Program.cs
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging((hosttingContext,logging)=>
{
logging.AddFilter("System", LogLevel.Warning);
logging.AddFilter("Microsoft", LogLevel.Warning);
logging.AddLog4Net();
})
;
}
3、配置Startup.cs文件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
loggerFactory.AddLog4Net();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
3、新建配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="DebugAppender" type="log4net.Appender.DebugAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<!--指定日记记录方式,以滚动文件的方式(文件记录)-->
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<!--日志路径-->
<file value="Log/" />
<!--是否是向文件中追加日志-->
<appendToFile value="true" />
<!--log保留天数-->
<param name= "MaxSizeRollBackups" value= "10"/>
<!--每个文件最大1M-->
<param name="maximumFileSize" value="1MB" />
<!--日志根据日期滚动-->
<param name="RollingStyle" value="Date" />
<!--日志文件名格式为:logs_20080831.log-->
<param name="DatePattern" value=""logs_"yyyyMMdd".log"" />
<!--日志文件名是否是固定不变的-->
<param name="StaticLogFileName" value="false" />
<!--布局-->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="DebugAppender" />
<appender-ref ref="RollingFile" />
</root>
</log4net>