Learn more about the. Net Core Web API Development Series "10": Working with logs

Source: Internet
Author: User

Series Catalogue

Learn more about the. Net Core WEB API Development Series Catalog

The source code involved in this series: Https://github.com/seabluescn/Blog_WebApi

I. Overview of this article

This article describes the use of logs, including system default console logs and third-party Nlog log management.

Second, use the system console log

1. Use the built-in log

[Produces ("Application/json")] [Route ("api/article")]     Public classArticlecontroller:controller {Private ReadOnlyILogger _logger;  PublicArticlecontroller (Salescontext context, ilogger<articlecontroller>logger) {          _logger=logger; } [HttpGet ("Logger")]         Public voidTestlogger ()        {_logger. Logcritical ("logcritical"); _logger. LogError ("LogError"); _logger. Logwarning ("logwarning"); _logger. Loginformation ("loginformation"); _logger. Logdebug ("Logdebug"); return; }    }

Only the first three records are visible by default:

The main reason is that the lowest level of the log defaults to warring, and if you want to display additional level logs, you need to modify the Application.json file.

{"    Logging": {    "includescopes": false,    "Debug": {      "LogLevel": {        "Default": "Error"      }    },    "Console": {      "LogLevel": {        "Default": "infomation"    }  }}

The log-level precedence is in the following order:

Critical > Error > Warning > Information > Debug

Adjusting the log level to information or debug will show too much unrelated log information, you can configure the default level to warring, and the log level of your own project namespace is Debug.

"Console": {      "LogLevel": {"        Default": "Warning",        "saleservice.controllers": "DEBUG"      }    }

2. Some notes

1) The current log can work properly, the project published to the Linux environment, by configuring the supervisor can be output to the file system of the console, it is recommended to use the debug log level in the debugging environment, and in the build environment using the error log level. The contents of the configuration supervisor can be consulted as follows: The step-up learning. Net Core WEB API Development Series "7": Project release.

2) If you know a little bit about dependency injection (DI), you can understand that our use of ILogger in Controoler is in the form of a standard constructor injection, but the problem is that the user is not registering the service, In fact, the system in the Createdefaultbuilder to help us register the log service. You can see a few snippets of source code:

Createdefaultbuilder:
usingSystem;usingSystem.IO;usingSystem.Reflection;usingMicrosoft.AspNetCore.Builder;usingMicrosoft.AspNetCore.Hosting;usingMicrosoft.AspNetCore.Http;usingMicrosoft.AspNetCore.Routing;usingMicrosoft.Extensions.Configuration;usingMicrosoft.Extensions.DependencyInjection;usingMicrosoft.Extensions.Logging;namespacemicrosoft.aspnetcore{     Public Static classwebhost {         Public StaticIwebhostbuilder Createdefaultbuilder (string[] args) {            returnWebhostbuilderiisextensions.useiisintegration (Hostingabstractionswebhostbuilderextensions.usecontentroot ( Webhostbuilderkestrelextensions.usekestrel (NewWebhostbuilder ()), Directory.GetCurrentDirectory ()). Configureappconfiguration (Delegate(webhostbuildercontext hostingcontext, Iconfigurationbuilder config) {ihostingenvironment h Ostingenvironment=hostingcontext.hostingenvironment; Jsonconfigurationextensions.addjsonfile (jsonconfigurationextensions.addjsonfile (config,"Appsettings.json",true,true),string. Format ("appsettings. {0}.json", Hostingenvironment.environmentname),true,true); if(Hostingenvironmentextensions.isdevelopment (hostingenvironment)) {Assembly ASSEMBL Y= Assembly.Load (NewAssemblyName (Hostingenvironment.applicationname)); if(Assembly! =NULL) {usersecretsconfigurationextensions.addusersecrets (config, assembly, true);                }} environmentvariablesextensions.addenvironmentvariables (config); if(Args! =NULL) {commandlineconfigurationextensions.addcommandline (config, args); }            }). Configurelogging (Delegate(Webhostbuildercontext hostingcontext, Iloggingbuilder logging) { Loggingbuilderextensio Ns. Addconfiguration (Logging, hostingContext.Configuration.GetSection ( "Logging")); Logging.                Addconsole (); Logging.            Adddebug (); })). Usedefaultserviceprovider (Delegate(Webhostbuildercontext context, serviceprovideroptions options) {options. Validatescopes=hostingenvironmentextensions.isdevelopment (context.            Hostingenvironment);        }); }    }}
Addconsole:
usingSystem;usingMicrosoft.Extensions.Configuration;usingMicrosoft.Extensions.DependencyInjection;usingMicrosoft.Extensions.Logging.Console;namespacemicrosoft.extensions.logging{     Public Static classconsoleloggerextensions {         Public StaticIloggingbuilder Addconsole ( ThisIloggingbuilder Builder) { Builder. Services.addsingleton <iloggerprovider, consoleloggerprovider> (); returnBuilder; }           }}

Third, the use of Nlog

1. Get the package through NuGet:NLog.Web.AspNetCore

2, modify the Startup class Configure method:

  Public classStartup { PublicStartup (iconfiguration configuration) {Configuration=configuration; }         PublicIConfiguration Configuration {Get; }

//This method gets called by the runtime. Use this method to configure the HTTP request pipeline. Public voidConfigure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory) {Loggerf Actory. Addnlog (); Loggerfactory.configurenlog ("Nlog.config");//if the default profile Nlog.config is used, the statement can omit } }

The contents of the Nlog.config configuration file are as follows:

<?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" > <targets> <target xsi:type= "File" name= "logfile" Filename= "${basedir}/logs/${shortdate}_all.log" keepfileopen= "false" layout= "${longdate}|${callsite:filename= True}|${uppercase:${level}}|${message} ${exception} "/> <target xsi:type=" File "name=" Debugfile "FileName=" ${ Basedir}/logs/${shortdate}_debug.log "keepfileopen=" false "layout=" ${longdate}|${callsite:filename=true}|${ Uppercase:${level}}|${message} ${exception} "/> <target xsi:type=" File "name=" Errfile "FileName=" ${basedir}/ Logs/${shortdate}_error.log "keepfileopen=" false "layout=" ${longdate}|${callsite:filename=true}|${uppercase:${ Level}}|${message} ${exception} "/> </targets> <rules> <logger name=" * "level=" Debug "writeto=" Debu Gfile "/> <logger name=" * "level=" Error "writeto=" Errfile "/> <loggeR name= "*" minlevel= "Trace" writeto= "logfile"/> </rules></nlog> 

Modify the configuration file when the project is published, leaving only Errfile.

That's all the code, and the code in the controller doesn't have to be modified.

3, two points of attention

1) At present, we have adopted nlog to log records, the system default log is still working, the project is recommended to change the system default log level to Error,nlog output log only retain errfile, so as not to cause wasted server disk space.

2) When the project is published, the Nlog.config file may not be published to the target directory, and the file properties of the file need to be modified:

Learn more about the. Net Core Web API Development Series "10": Working with logs

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.