如何将log4net配置写入appsettings.json?

Dev*_*rof 9 log4net log4net-configuration asp.net-core-2.0

我已经实现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>
Run Code Online (Sandbox Code Playgroud)

这是我的XML配置.

我发现这个问题,其所提及log4net don't support Json projects.是否可以将其配置写入appsettings.json.

Dev*_*rof 6

也许这不是正确的方法,但是无论如何我设法使用了我的log4net.configin appSettings.json. 我把我的答案放在这里,所以如果他们不想为那里的项目使用额外的配置文件,它可以帮助某人。

所以我所做的就像是将我的XML转换为JSON并使用JSON作为我的字符串,appSettings.json然后我使用以下代码读取字符串。

应用设置.json

{
  "ConnectionStrings": {
    "LoggerConfig": "Config string"
  }
}
Run Code Online (Sandbox Code Playgroud)

JsonXML转换使用Newtonsoft.Json

 string xmlElement = _configuration["ConnectionStrings:LoggerConfig"];
 XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(xmlElement);
 XmlConfigurator.Configure(logRepository, GenerateStreamFromString(doc.InnerXml));
Run Code Online (Sandbox Code Playgroud)

此代码用于将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;
        }
Run Code Online (Sandbox Code Playgroud)

它工作正常。

在这里,我曾经首先转换 myXML to JSON并再次JSON to XML将其用作 a log4net config,但是如果有人想要,则直接将 XML 用作字符串,因此它会减少一些代码。


Sta*_*cev 5

如果您使用Microsoft.Extensions.Logging.Log4Net.AspNetCore nuget 包,有一种方法可以将 log4net 配置保留在 appsettings.json 中(但老实说不是很有用)。

您可以写入appsettings.json(或不同环境的appsettings.Environment.json)规则来覆盖log4net配置文件中的节点。

文档

从 appsettings.json 设置日志记录级别的示例。

应用程序设置.json:

{
  "Log4NetCore": {
    "PropertyOverrides": [
      {
        "XPath": "/log4net/root/level",
        "Attributes": {
          //"value": "ALL"
          //"value": "DEBUG"
          //"value": "INFO"
          "value": "WARN"
          //"value": "ERROR"
          //"value": "FATAL"
          //"value": "OFF"
        }
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

您仍然需要 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>
Run Code Online (Sandbox Code Playgroud)

在 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();
    }
}
Run Code Online (Sandbox Code Playgroud)