如果您使用
Microsoft.Extensions.Logging.Log4Net.AspNetCore nuget包,有一种方法可以在appsettings.json中保留log4net配置(但老实说不太实用)。
您可以将规则写入appsettings.json(或appsettings.Environment.json以适应不同的环境),以覆盖来自log4net配置文件的节点。
文档
从appsettings.json设置日志记录级别的示例。
appsettings.json:
{
"Log4NetCore": {
"PropertyOverrides": [
{
"XPath": "/log4net/root/level",
"Attributes": {
"value": "WARN"
}
}
]
}
}
你仍需要一个log4net配置文件,并在其中指定你想要从appsettings.json中覆盖的节点:
<?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="example.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<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>
在 Startup.cs 中进行注册:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var loggingOptions = this.Configuration.GetSection("Log4NetCore")
.Get<Log4NetProviderOptions>();
loggerFactory.AddLog4Net(loggingOptions);
app.UseMvc();
}
}