Detailed. net core diary records

Time:2019-8-8

ASP.NET Core has built-in log components. Unfortunately, after looking at Microsoft’s official documents, it seems that it is impossible to store logs directly in files or databases. It can only implement or reference third-party log components by itself.

The following are the usage records of Nlog and log4net

Nlog use

Search to add Nuget packages

Nlog
Nlog.Web.AspNetCore

Create a new XML file and rename it nlog. config

The XML content is as follows (configurable log directory name, output format):


<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  autoReload="true"
  internalLogLevel="Warn"
  internalLogFile="internal-nlog.txt">

 <!--define various log targets-->
 <targets>

 <!--write logs to file-->
 <target xsi:type="File" name="allfile" fileName="Logs/service-${shortdate}.log"
     layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

 </targets>

 <rules>
 <!--All logs, including from Microsoft-->
 <logger name="*" minlevel="Trace" writeTo="allfile" />
 </rules>
</nlog>

Export nlog.config settings to directories

Configuration in Startup class

Namespaces need to be introduced:

using NLog.Extensions.Logging;

using NLog.Web;

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactor)
{
 // Using Nlog
 loggerFactor.AddNLog();
 // Introducing configuration files
 env.ConfigureNLog("nlog.config");
 if (env.IsDevelopment())
 {
  app.UseDeveloperExceptionPage();
 }
 else
 {
  app.UseExceptionHandler("/Error");
 }
 app.UseStaticFiles();
 app.UseCookiePolicy();

 app.UseMvc();
}

Use in code

There are two ways as follows:

1. Injection Form


public class IndexModel : PageModel
{
 private ILogger<IndexModel> _logger;
 public IndexModel(ILogger<IndexModel> logger)
 {
  _logger = logger;
 }
 public string Customer { get; set; }
 public void OnGet()
 {
  _logger.LogWarning("111111111111111111111");
  Customer = "123456";
 }
}

2. Obtaining Instance Form


private static Logger Logger = LogManager.GetCurrentClassLogger();
public static void Main(string[] args)
{
 Logger.Error("22222222222222222222222222222");
 Logger.Info("333333333333333333333333333333");
}

 log4net

Log4net already supports net core. Let’s see how to configure it under net core. It’s a little different from previous versions.

Use conventions, refer to Nuget

log4net

New configuration file


<?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="logs/" /> 
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <staticLogFileName value="false" />
  <datePattern value="yyyy-MM-dd'.log'" />
  <maxSizeRollBackups value="7" />
  <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>

Configuration file related instructions, you can see another article point I jump

Configure log4Net in StartUp. CS

public static ILoggerRepository repository { get; set; }

public Startup(IConfiguration configuration)
{
 Configuration = configuration;
 //log4net
 repository = LogManager.CreateRepository("NETCoreRepository");
 // Specify configuration files
 XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
}

Use in Controller


private ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(ValuesController));

[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
 log.Info(1111111111111111111);
 return new string[] { "value1", "value2" };
}

Use in console


ILoggerRepository repository = LogManager.CreateRepository("NETCoreRepository");

XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));

ILog log = LogManager.GetLogger(repository.Name,"NETCorelog4net");
 
log.Info("test log");

The above is a detailed integration of. net core diary records introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave a message for me, Xiaobian will reply to you in time. Thank you very much for your support to developpaer.