How to write log4net config into appsettings.json?

南笙酒味 提交于 2020-07-17 06:38:52

问题


I have implemented log4net into .NET core 2.0, to log into a text file. As log4net have a config file, which is having XML configuration in it. So, I have created a separate file log4net.config to set its configuration and it is working fine. But I want to set its configuration into appsettings.json. Is it possible to write the log4net configuration into 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>

this is my XML configuration.

I have found this question in which it is mentioned that log4net don't support Json projects. Is it possible to write its configuration into appsettings.json.


回答1:


Maybe it is not the right way but, anyhow I managed to use my log4net.config in appSettings.json. I am putting my answer here so it can help someone if they don't want to use an extra config file for there project.

So what I have done is like by converting my XML into JSON and used the JSON as a string on my appSettings.json after that I use the following code to read the string.

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));

This code is used to convert the JSON into XML but it will not provide the XML content as Element so, I used it as a stream. For converting the string into a stream I used the following code.

        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;
        }

and it works fine.

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.




回答2:


If you using Microsoft.Extensions.Logging.Log4Net.AspNetCore nuget package, there is a way keep log4net config in appsettings.json (but honestly not very usable).

You can write into appsettings.json (or appsettings.Environment.json for different environments) rules overriding nodes from log4net config file.

Documentation

Example of setting the logging level from 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"
        }
      }
    ]
  }
}

You still needs log4net config file with nodes which you want override from 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>

Registration in 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();
    }
}


来源:https://stackoverflow.com/questions/52070748/how-to-write-log4net-config-into-appsettings-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!