如何将 log4net 配置写入 appsettings.json?
How to write log4net config into appsettings.json?
我已将 log4net
实施到 .NET core 2.0
中,以登录文本文件。由于 log4net 有一个配置文件,其中包含 XML configuration
。所以,我创建了一个单独的文件 log4net.config
来设置它的配置,它工作正常。但是我想把它的配置设置成appsettings.json
。是否可以将log4net配置写入appsettings.json
.
<appSettings>
<add key="IsLog" value="True" />
<add key="MaxThreads" value="3" />
</appSettings>
<log4net debug="false">
<root>
<level value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
</root>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="./logs/logfile.txt" />
<appendToFile value="false" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="-1" />
<maximumFileSize value="50GB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
</log4net>
这是我的 XML 配置。
我找到了这个 question,其中提到 log4net don't support Json projects
。能不能把它的配置写成appsettings.json
.
也许这不是正确的方法,但无论如何我设法在 appSettings.json
中使用了我的 log4net.config
。我把我的答案放在这里,如果他们不想为项目使用额外的配置文件,它可以帮助他们。
所以我所做的就是将 XML 转换为 JSON 并使用 JSON 作为我 appSettings.json
上的字符串,之后我使用以下代码读取字符串。
appSettings.json
{
"ConnectionStrings": {
"LoggerConfig": "Config string"
}
}
Json to XML Conversion using Newtonsoft.Json
string xmlElement = _configuration["ConnectionStrings:LoggerConfig"];
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(xmlElement);
XmlConfigurator.Configure(logRepository, GenerateStreamFromString(doc.InnerXml));
此代码用于将JSON转换为XML但不会提供XML 内容作为 Element 因此,我将其用作流。
为了将字符串转换为流,我使用了以下代码。
public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
而且效果很好。
Here I used to convert first my XML to JSON
and again JSON to XML
to
use it as a log4net config
, but if anyone wants then use XML
directly as a string, So it will reduce some code.
如果你使用 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": "ALL"
//"value": "DEBUG"
//"value": "INFO"
"value": "WARN"
//"value": "ERROR"
//"value": "FATAL"
//"value": "OFF"
}
}
]
}
}
您仍然需要 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; }
// 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)
{
// Add these lines
var loggingOptions = this.Configuration.GetSection("Log4NetCore")
.Get<Log4NetProviderOptions>();
loggerFactory.AddLog4Net(loggingOptions);
app.UseMvc();
}
}
我已将 log4net
实施到 .NET core 2.0
中,以登录文本文件。由于 log4net 有一个配置文件,其中包含 XML configuration
。所以,我创建了一个单独的文件 log4net.config
来设置它的配置,它工作正常。但是我想把它的配置设置成appsettings.json
。是否可以将log4net配置写入appsettings.json
.
<appSettings>
<add key="IsLog" value="True" />
<add key="MaxThreads" value="3" />
</appSettings>
<log4net debug="false">
<root>
<level value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
</root>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="./logs/logfile.txt" />
<appendToFile value="false" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="-1" />
<maximumFileSize value="50GB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
</log4net>
这是我的 XML 配置。
我找到了这个 question,其中提到 log4net don't support Json projects
。能不能把它的配置写成appsettings.json
.
也许这不是正确的方法,但无论如何我设法在 appSettings.json
中使用了我的 log4net.config
。我把我的答案放在这里,如果他们不想为项目使用额外的配置文件,它可以帮助他们。
所以我所做的就是将 XML 转换为 JSON 并使用 JSON 作为我 appSettings.json
上的字符串,之后我使用以下代码读取字符串。
appSettings.json
{
"ConnectionStrings": {
"LoggerConfig": "Config string"
}
}
Json to XML Conversion using
Newtonsoft.Json
string xmlElement = _configuration["ConnectionStrings:LoggerConfig"];
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(xmlElement);
XmlConfigurator.Configure(logRepository, GenerateStreamFromString(doc.InnerXml));
此代码用于将JSON转换为XML但不会提供XML 内容作为 Element 因此,我将其用作流。 为了将字符串转换为流,我使用了以下代码。
public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
而且效果很好。
Here I used to convert first my
XML to JSON
and againJSON to XML
to use it as alog4net config
, but if anyone wants then use XML directly as a string, So it will reduce some code.
如果你使用 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": "ALL"
//"value": "DEBUG"
//"value": "INFO"
"value": "WARN"
//"value": "ERROR"
//"value": "FATAL"
//"value": "OFF"
}
}
]
}
}
您仍然需要 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; }
// 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)
{
// Add these lines
var loggingOptions = this.Configuration.GetSection("Log4NetCore")
.Get<Log4NetProviderOptions>();
loggerFactory.AddLog4Net(loggingOptions);
app.UseMvc();
}
}