. NET Core log4net, corelog4net

Source: Internet
Author: User
Tags configuration settings log4net

. NET Core log4net, corelog4net

Log4net. NET Core is used. It has been released for a while since version 2.0.6.

Previously, we introduced the use of NLog. NET Core. ASP. NET Core development-Logging used NLog to write log files.

ASP. NET Core has built-in log support and can be easily output to the console. Use log4net to write logs to the file and output console.

 

. NET Core project usage

Create a. NET Core project and selectConsole Application.

Add reference:

Install-Package log4net

 

Use simple configuration to output logs to the console, which is slightly different from the previous. NET version. You need to specify the Repository.

Public static void Main (string [] args) {ILoggerRepository repository = LogManager. createRepository ("NETCoreRepository"); // simple configuration by default, which is output to BasicConfigurator on the console. configure (repository); ILog log = LogManager. getLogger (repository. name, "NETCorelog4net"); log. info ("NETCorelog4net log"); log. info ("test log"); log. error ("error"); log. info ("linezero"); Console. readKey ();}

The running program is shown as follows:

 

Add the configuration to output it to the file.

Add a configuration file to the project. Add log4net. config as follows:

<?xml version="1.0" encoding="utf-8" ?><configuration>  <!-- This section contains the log4net configuration settings -->  <log4net>    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">      <layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" />    </appender>        <appender name="FileAppender" type="log4net.Appender.FileAppender">      <file value="log-file.log" />      <appendToFile value="true" />      <layout type="log4net.Layout.PatternLayout">        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />      </layout>    </appender>    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">      <file value="logfile/" />      <appendToFile value="true" />      <rollingStyle value="Composite" />      <staticLogFileName value="false" />      <datePattern value="yyyyMMdd'.log'" />      <maxSizeRollBackups value="10" />      <maximumFileSize value="1MB" />      <layout type="log4net.Layout.PatternLayout">        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />      </layout>    </appender>    <!-- Setup the root category, add the appenders and set the default level -->    <root>      <level value="ALL" />      <appender-ref ref="ConsoleAppender" />      <appender-ref ref="FileAppender" />      <appender-ref ref="RollingLogFileAppender" />    </root>  </log4net></configuration>

Three Appender are defined here, and ALL logs at the log level are recorded.

The code for changing Program. cs is as follows:

        public static void Main(string[] args)        {            ILoggerRepository repository = LogManager.CreateRepository("NETCoreRepository");            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));            ILog log = LogManager.GetLogger(repository.Name,"NETCorelog4net");            log.Info("NETCorelog4net log");            log.Info("test log");            log.Error("error");            log.Info("linezero");            Console.ReadKey();        }

The specified configuration file is added. The running program will generate a folder and a file, because the ConsoleAppender is redefined, and the console output is also different.

 

ASP. NET Core project usage

The same applies to ASP. NET Core. You can specify the Repository in Program. cs or Startup. cs, and then obtain the object usage in the Controller or middleware.

The following code initializes log4net in the Startup constructor:

    public class Startup    {        public static ILoggerRepository repository { get; set; }        public Startup(IHostingEnvironment env)        {            var builder = new ConfigurationBuilder()                .SetBasePath(env.ContentRootPath)                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)                .AddEnvironmentVariables();            Configuration = builder.Build();            repository = LogManager.CreateRepository("NETCoreRepository");            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));        }

Then add a record log in Configure

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)        {            var log = LogManager.GetLogger(repository.Name,typeof(Startup));            log.Info("test");

 

Added the following in HomeController:

        private ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(HomeController));        public IActionResult Index()        {            log.Info("index view");            log.Error("Controller Error");            return View();        }

The result of running the application is as follows, and the corresponding file will be logged.

 

 

Encoding references and codes must be added to output Chinese garbled characters. The NLog article has an introduction. There is no problem with writing to the log file.

 

Reference:

Http://logging.apache.org/log4net/release/manual/configuration.html

Http://logging.apache.org/log4net/release/config-examples.html

 

If you think this article is helpful to you, click"Recommendation", Thank you.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.