Detailed explanation of how to add log function to. Net core project

Time:2019-11-4

I. Microsoft’s built-in log component

When a new web API project is created using templates in. Net core, the logging function is automatically added. Just inject ilogger into the controller. Namespace is:Microsoft.Extensions.Logging

It will be found that only error is printed to the console, and trace is not printed. That’s because in appsetting.json, the logging > console > default level is debug, and the log level is greater than or equal to debug before it is output to the console. Let’s talk about it hereLogLevel:Trace<Debug<Information<Warning<Error<Critical<None

When you open the appsettings.development.json file, you will find that it is different from the appsettings.json configuration. As follows:


{
 "Logging": {
 "IncludeScopes": false,
 "LogLevel": {
 "Default": "Debug",
 "System": "Information",
 "Microsoft": "Information"
 }
 }
}

For example:

"System": "Information" Indicates that a class whose namespace starts with system and whose log level is greater than or equal to information will be output to the console.

"Default": "Debug" Indicates that the namespace log level divided by system and Microsoft is approximately equal to debug before it is output to the console.

When did you read the configuration in appsettings.json In fact, in the programWebHost.CreateDefaultBuilder(arge)

Open source discovery

Of course, we can not use the default configuration provided by Microsoft

public class Program
 {
 public static void Main(string[] args)
 {
  //Specify profile path
  var configBuilder = new ConfigurationBuilder()
     .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile($"appsettings.json", true, true)
    .AddJsonFile($"appsettings.{EnvironmentName.Development}.json", true, true);

  var config = configBuilder.Build();
  
  var host = new WebHostBuilder()
   .UseKestrel()
   .UseStartup<Startup>()
   .UseContentRoot(Directory.GetCurrentDirectory())
   . useurls (config ["Appsettings: URL") // set the start address
   .Build();
  host.Run();
 }
 }

The configuration file is:


{
 "AppSettings": {
 "Url": "http://0.0.0.0:6000"
 },
 "Logging": {
 "IncludeScopes": false,
 "Debug": {
 "LogLevel": {
 "Default": "Info"
 }
 },
 "Console": {
 "LogLevel": {
 "Default": "Warning"
 }
 }
 }
}

Startup is:

public class Startup
 {
 public IConfiguration Configuration { get; private set; }
 Public startup (ihostingenvironment Env) // inject ihostingenvironment into the constructor 
 {
  Configuration = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile($"appsettings.json")
    .Build();
 }
 public void ConfigureServices(IServiceCollection services)
 {
  services.AddMvc();
 }

 public void Configure(IApplicationBuilder app,
  IHostingEnvironment env,
  ILoggerFactory loggerFactory)
 {
  if (env.IsDevelopment())
  {
  app.UseDeveloperExceptionPage();
  }
  //Add console output
  loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  loggerFactory.AddDebug();

  app.UseMvc();
 }
 }

However, the built-in log component provided by Microsoft does not record logs to files or databases. Here’s NLog

Two, NLog

First add NLog using nuget, and then add the following code to configure in startup

public void Configure(IApplicationBuilder app,
  IHostingEnvironment env,
  ILoggerFactory loggerFactory)
 {
  if (env.IsDevelopment())
  {
  app.UseDeveloperExceptionPage();
  }
  //Add console output
  loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  loggerFactory.AddDebug();

  Loggerfactory. Addnlog(); // add NLog
  NLog. Logmanager. Loadconfiguration ([email protected] "{env. Contentrootpath} / NLog. Config"); // specifies the configuration file of NLog

  app.UseMvc();
 }

Configure NLog’s profile

<?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">-->
 <targets>
 <target name="allfile" xsi:type="File" fileName="./logs/${shortdate}/all.log" layout="${longdate}|${message} ${exception}" />
 <target name="debugfile" xsi:type="File" fileName="./logs/${shortdate}/debug.log" layout="${longdate}|${message} ${exception}" />
 <target name="infofile" xsi:type="File" fileName="./logs/${shortdate}/info.log" layout="${longdate}|${message} ${exception}" />
 <target name="warnfile" xsi:type="File" fileName="./logs/${shortdate}/warn.log" layout="${longdate}|${message} ${exception}" />
 <target name="errorfile" xsi:type="File" fileName="./logs/${shortdate}/error.log" layout="${longdate}|${message} ${exception}" />
 <target name="fatalfile" xsi:type="File" fileName="./logs/${shortdate}/fatal.log" layout="${longdate}|${message} ${exception}" />
   < target name = "network" XSI: type = "network" address = "UDP: // chinacloudapp. CN: 4561" layout = "development" ${longtate} "${event properties: item = eventid. ID}" ${logger} "${uppercase: ${level}"} "${message}" ${exception} "/ > // output the log through the network
 < target name = "debug" XSI: type = "console" / > // output logs to the console
 </targets>

 <rules>
 <logger name="*" minlevel="Trace" writeTo="allfile,debuge" />
 <logger name="*" level="Info" writeTo="infofile" />
 <logger name="*" level="debug" writeTo="debugfile" />
 <logger name="*" level="warn" writeTo="warnfile" />
 <logger name="*" level="error" writeTo="errorfile" />
 <logger name="*" level="fatal" writeTo="fatalfile" />
 
 </rules>
</nlog>

xsi:type=“File”The storage log is in file format,

xsi:type="Console" Represents console output.

fileName="./logs/${shortdate}/all.log" Represents the storage file path.

layout="${longdate}|${message} ${exception}" Represents the layout of the contents of the file.

The rules tab indicates that the corresponding level of logs is written to the corresponding target. as

<logger name="*" level="Info" writeTo="infofile" /> Indicates that the log with level info is written to the file with target name infofile.

<logger name="*" minlevel="Trace" writeTo="allfile,debuge" /> Indicates that logs with a log level greater than trace are written to target names allfile and debug (console output).

Also in use, you only need to inject ilogger where it is used, and you can use it.

summary

The above is the whole content of this article. I hope that the content of this article has a certain reference learning value for everyone’s study or work. If you have any questions, you can leave a message and exchange. Thank you for your support for developepaar.