当前位置:网站首页>NLog details

NLog details

2022-06-23 23:31:00 Brother Li Yu

Nlog Detailed explanation

zero 、 List of articles

One 、Nlog Detailed explanation

1、 summary

NLog It's based on .NET The logging class library written by the platform , We can use NLog Add perfect trace debugging code to your application . It can be in any kind of .NET Language output with context (contextual information) Debug diagnostic information , Configure its presentation style according to your preference and send it to one or more output targets (target) in .

Official website address :https://nlog-project.org/

Document address :https://github.com/NLog/NLog/wiki

2、 Quick start

(1)nuget Import assembly

NLog   Version based on 5.0 edition ,Net5

(2) Code implementation

// Create a profile object 
var config = new NLog.Config.LoggingConfiguration();
// Create log write destination 
var logfile = new NLog.Targets.FileTarget("logfile") { FileName = $"logs/{DateTime.Now.ToString("yyyy-MM-dd")}.txt" };
// Add log routing rule 
config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
// Profile validation 
LogManager.Configuration = config;
// How to create a logging object 1
Logger Logger = LogManager.GetCurrentClassLogger();
// How to create a logging object 2, Manual naming 
Logger Logger2 = LogManager.GetLogger("MyLogger");
// Log out 
Logger.Debug(" I hit Nlog journal !");

(3) Running results

image-20220619151929015

3、 Support file configuration

(1)nuget Import assembly

NLog
NLog.Config   The configuration file 

(2) Profile path

NLog At startup, the configuration file will be found in some standard paths , Configure automatically :

  • about stand-alone *.exe Applications , The following paths will be queried :

    • Standard application configuration files ( Usually applicationname.exe.config)
    • Under the application directory applicationname.exe.nlog file
    • Under the application directory NLog.config file (Name sensitive; using docker dotnet core)
    • NLog.dll In the directory NLog.dll.nlog file (only if NLog isn’t installed in the GAC)
  • about http://ASP.NET Applications , The following files will be queried :

    • standard web Application files web.config
    • web.config In the directory web.nlog file
    • Under the application directory NLog.config file
    • NLog.dll In the directory NLog.dll.nlog file (only if NLog isn’t installed in the GAC)
  • about .NET Compact Framework project , Application configuration files (*.exe.config) And environment variables are not recognized . therefore ,NLog Query only in the following path :

    • Under the application directory applicationname.exe.nlog file
    • Under the application directory NLog.config file
    • NLog.dll In the directory NLog.dll.nlog file (only if NLog isn’t installed in the GAC)
  • about Xamarin Android project ,assert In folder NLog.config The file will be loaded automatically . If the configuration file name is different , You can execute the following commands :

    • LogManager.Configuration = new XmlLoggingConfiguration(“assets/someothername.config");

(3) The configuration file

introduce NLog.Config after , The project will automatically add a NLog.Config The configuration file , This is the default configuration file , This file is not in the project folder and needs to be copied , The right-click attribute of the configuration file must be set to Always copy .

While the program is running , It will load automatically NLog.Config As Nlog Configuration of .

XML Detailed description in the document ,rules Configure routing rules , targets Configure output targets .

<?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" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

  <!-- optional, add some variables https://github.com/nlog/NLog/wiki/Configuration-file#variables -->
  <variable name="myvar" value="myvalue"/>

  <!-- See https://github.com/nlog/nlog/wiki/Configuration-file for information on customizing logging rules and outputs. -->
  <targets>

    <!-- add your targets here See https://github.com/nlog/NLog/wiki/Targets for possible targets. See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers. -->

    <!-- Write events to a file with the date in the filename. <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message}" /> -->
  </targets>

  <rules>
    <!-- add your logging rules here -->

    <!-- Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f" <logger name="*" minlevel="Debug" writeTo="f" /> -->
  </rules>
</nlog>

Remove comments , The most compact version is 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>
	<!-- Output target :name name f,xsi:type Output type file , fileName Output to the program root directory logs In the folder ,  Generate by date log File name , layout Format of generated content -->
    <target name="f" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message}" />
  </targets>
  <rules>
	  <!-- Log routing rules : The lowest level Debug, Output to target The goal is f-->
    <logger name="*" minlevel="Debug" writeTo="f" />
  </rules>
</nlog>

(4) Code implementation

// Create a logging object 
Logger Logger = NLog.LogManager.GetCurrentClassLogger();
// Log out 
Logger.Debug(" I hit Nlog journal !");

(5) Running results

image-20220619152433357

4、 Configuration file details

(1) Global configuration

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

Suggest throwExceptions The value of the set “false”, In this way, the problems caused by logging will not cause the application to crash .

autoReload  Whether to allow automatic loading without restarting the program after modifying the configuration file 
throwExceptions  The internal log system throws an exception 
internalLogLevel  Optional Trace|Debug|Info|Warn|Error|Fatal Determine the level of internal logging  Off  close 
internalLogFile  Write the internal debugging and exception information into the specified file 

(2) Root element

In the root element of the configuration file , We can specify the following child elements . The first two must be set , The other three are optional settings .

  1. targets: Define the output destination of the log
  2. rules: Define routing rules for log information
  3. extensions: Define from other dll File loaded NLog Extension module
  4. include: Import external configuration file
  5. variable: Define the variables used in the configuration file

(3)targets Define the output destination of the log

<targets>
    <target name="f" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message}" maxArchiveFiles="5" archiveAboveSize="10240" archiveEvery="Day"/>
</targets>

Nlog Allows the user to configure a single file size , The content is too long and the efficiency is too slow , After configuring the size , Nlog A new copy of the file is automatically created , Insert new log output .

maxArchiveFiles: Maximum number of replica files allowed to be generated

archiveAboveSize: Maximum capacity allowed for a single file

archiveEvery: Generated by day

name: The name of the output destination , be used for rules The rules of the middle road writeTo Appoint

fileName: Contains the path and file name of the complete makefile

xsi:type: The output type

Chainsaw
ColoredConsole 
Console
Database
Debug
Debugger
EventLog
File
LogReceiverService
Mail
Memory
MethodCall
Network
NLogViewer
Null
OutputDebugString
PerfCounter
Trace
WebService

layout: Used to specify the format of output content , grammar “${ attribute }”, You can insert context information into the log .

$ {
    cached} -   Apply cache to another layout output .
$ {
    db-null} -  Render for database DbNull
$ {
    exception} -  By calling Logger The exception information provided by one of the methods 
$ {
    level} -  The level of logging ( for example ERROR,DEBUG) Or rank ordinal number ( Numbers )
$ {
    literal} -  String text .( Text )- Useful , To avoid parentheses 
$ {
    logger} -  Recorder name .GetLogger,GetCurrentClassLogger etc. 
$ {
    message} - ( Formatted ) Log message .
$ {
    newline} -  Wrap text .
$ {
    object-path} -   Render the object's ( nesting ) attribute 
$ {
    onexception} -   The internal layout is output only if an exception is defined for the log message .
$ {
    var} -  Render variables 
 Call site and stack trace -------------------------------------------------------------
$ {
    callsite} -  Call site ( Class name , Method name and source information )
$ {
    callsite-linenumber} -  Call site source line number .
$ {
    stacktrace} -  Render stack trace 
 Conditions ------------------------------------------------------------------------
$ {
    when} -   Output the internal layout only when the specified conditions are met .
$ {
    whenempty} -   When the internal layout produces an empty result , Output alternate layout .
 Context information -------------------------------------------------------------------
$ {
    activityid} -  take System.Diagnostics Trace associations ID Record it in the journal .
$ {
    all-event-properties} -  Record all event context data .
$ {
    event-context} -   Record event attribute data - Replace with $ {
    event-properties}
$ {
    event-properties} -  Record event attribute data - rename $ {
    event-context}
$ {
    gdc} -  Global diagnostic context item . A dictionary structure that contains values for each application instance .
$ {
    install-context} -  Installation parameters ( Pass to InstallNLogConfig).
$ {
    mdc} -  Mapping diagnostic context - Thread local structure .
$ {
    mdlc} -  Asynchronous mapping diagnostic context - Thread local structure .MDC The asynchronous version of 
$ {
    ndc} -  Nested diagnostic context - Thread local structure .
$ {
    ndlc} -  Asynchronous nested diagnostic context - Thread local structure .
 Special counter -----------------------------------------------------------------------
$ {
    counter} -  A counter value ( Add... To each layout rendering )
$ {
    guid} -  Globally unique identifier (GUID).
$ {
    sequenceid} -  Log serial number 
 Date and time ------------------------------------------------------------------
$ {
    date} -  Current date and time .
$ {
    longdate} -  Date and time , Use sortable long format `yyyy-MM-dd HH:mm:ss.ffff`.
$ {
    qpc} -  High precision timer , be based on QueryPerformanceCounter The value returned .
$ {
    shortdate} -  A short date , The format is yyyy-MM-dd.
$ {
    ticks} -  Of the current date and time “ Ticks” value .
$ {
     Time } -  stay 24 Hours , Sortable format HH Time for :MM:ss.mmm.
 Encoding and string conversion --------------------------------------------------------------
$ {
    json-encode} -   Use JSON Rules escape the output of another layout .
$ {
    left} -   The left half of the text 
$ {
     A lowercase letter } -   Convert the output of another layout to lowercase .
$ {
    norawvalue} -   Prevents the output of another layout renderer from being treated as the original value 
$ {
    pad} -   Apply fill to another layout output .
$ {
    replace} -   Replace the string in the output of another layout with another string . Regular expressions are optional 
$ {
    replace-newlines} -   Replace newline with another string .
$ {
    right} -   The right side of the text 
$ {
    rot13} -   Use ROT-13 decode “ encryption ” The text of .
$ {
    substring} -   Substring of text 
$ {
    trim-whitespace} -   Trim white space from the results of another layout renderer .
$ {
    uppercase} -   Convert the output of another layout to uppercase .
$ {
    url-encode} -   Encode the output of another layout , In order to offer URL Use .
$ {
    wrapline} -   Wrap the output of another layout with the specified length .
$ {
    xml-encode} -   Convert the output of another layout to XML Compatible .
 Environment and configuration files ----------------------------------------------------------------
$ {
    appsetting} -. config file  NLog.Extended Application configuration settings in 
$ {
    configsetting} -  come from appsettings.json or ASP.NET Core and .NET Core Values for other configurations in  NLog.Extensions.Logging NLog.Extensions.Hosting NLog.Web.AspNetCore
$ {
    environment} -  environment variable .( for example PATH,OSVersion)
$ {
    environment-user} -  User identity information ( user name ).
$ {
    } The registry  -  from Windows The value in the registry .
 Files and directories --------------------------------------------------------------------
$ {
    basedir} -  Base directory of the current application domain .
$ {
    currentdir} -  The current working directory of the application .
$ {
    file-contents} -  Render the contents of the specified file .
$ {
    filesystem-normalize} -   Filter the disallowed characters in the file name by replacing the file name with safe characters .
$ {
    } nlogdir -  among NLog.dll directory .
$ {
    specialfolder} -  System private folder path ( Include “ My documents ”,“ My music ”,“ Program files ”,“ desktop ” etc. ).
$ {
    tempdir} -  Temporary directory .
 Identification ----------------------------------------------------------------------
$ {
    identity} -  Thread identity information ( Name and authentication information ).
$ {
    windows-identity} -  Threads Windows Identity information ( user name )
$ {
    windows-identity} -  Threads Windows Identity information ( user name ) Nlog.WindowsIdentity
 Integration ----------------------------------------------------------------------
$ {
    gelf} -  Convert logs to GELF Format  NLog.GelfLayout  external 
$ {
    log4jxmlevent} -  And log4j,Chainsaw and NLogViewer Compatible XML Description of the incident .
 process , Threads and assemblies --------------------------------------------------------------
$ {
    appdomain} -  Current application domain .
$ {
    assembly-version} -  The version of the executable in the default application domain .
$ {
    gc} -  Information about the garbage collector .
$ {
    hostname} -  The hostname of the computer on which the process is running .
$ {
    local-ip} -  Local from the network interface IP Address .
$ {
    machinename} -  The name of the computer on which the process is running .
$ {
    performancecounter} -  Performance counters .
$ {
    processid} -  Identifier of the current process .
$ {
    processinfo} -  Information about running processes . for example StartTime,PagedMemorySize
$ {
    processname} -  The name of the current process .
$ {
    processtime} -  The format is HH:mm:ss.mmm The processing time of .
$ {
    threadid} -  Identifier of the current thread .
$ {
    threadname} -  The name of the current thread .
Silverlight------------------------------------------------------------------------
$ {
    document-uri} -  Load the current Silverlight Application's HTML Page URI.
$ {
    sl-appinfo} -  of Silverlight Information about the application .
Web,ASP.NET and ASP.NET Core----------------------------------------------------------
$ {
    ASPNET-appbasepath} - ASP.NET The basic path of the application ( Content root ) NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET application } - ASP.NET Application variables .  Web log 
$ {
    ASPNET Environmental Science } - ASP.NET Name of the environment  NLog.Web.AspNetCore
$ {
    ASPNET term } - ASP.NET`HttpContext` Item variable . NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET-MVC- action } - ASP.NET MVC denomination of dive  NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET-MVC controller } - ASP.NET MVC Controller name  NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET request } - ASP.NET Request variable . NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET- Requested contentType} - ASP.NET Content-Type head ( The embodiment applies / JSON) NLog.Web.AspNetCore
$ {
    ASPNET request , cookies } - ASP.NET Requested cookie The content of . NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET Request form } - ASP.NET Contents of the request form . NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET Ask the head of the newspaper } - ASP.NET Radical key / It's worth it . NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET Request host } - ASP.NET Request host . NLog.Web NLog.Web.AspNetCore
$ {
    aspnet-request-ip} -  client IP. NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET request - Method } - ASP.NET Request method (GET,POST etc. ). NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET request , fitted } - ASP.NET fitted / Net load  NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET- Query string requested } - ASP.NET Query string requested . NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET, Ask for a referral } - ASP.NET Request reference . NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET Requested URL} - ASP.NET request URL. NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET request , The user agent } - ASP.NET Request user agent . NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET- Responsive StatusCode} - ASP.NET The contents of the response status code . NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET conversation } - ASP.NET Session Variable . NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET- Of SessionID} - ASP.NET conversation ID The variable of . NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET-traceidentifier} - ASP.NET Tracking identification  NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET user - Of authType} - ASP.NET User authentication . NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET User's identity } - ASP.NET User variables . NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET user -isauthenticated} - ASP.NET User authentication ? NLog.Web NLog.Web.AspNetCore
$ {
    ASPNET-webrootpath} - ASP.NET Web Root path (wwwroot file ) NLog.Web NLog.Web.AspNetCore
$ {
    iis-site-name} - IIS The name of the website . NLog.Web NLog.Web.AspNetCore

(4)rules Define routing rules for log information

Routing order will affect log printing . Route matching logic is sequence matching .

Logs can be output at different levels , Log rules rules The output log level can be controlled . Different levels of logs represent the importance of logs , For example, some debug Level logs are controlled not to be output in the production environment , To reduce the size of the log file .

<rules>
    <logger name="*" minlevel="Debug" writeTo="file" />
</rules>

name: Name of recorder .

minlevel : Minimum log level .

maxlevel: Maximum log level .

level: Single log level .

levels: A series of log levels , Separated by commas .

final: Whether it is the last matching route ,true It means that the matching ends here .

writeTo: A set of targets that the log should be written to when the rules match , Separated by commas . Namely tagets Corresponding name.

The log levels are as follows , From top to bottom , The level increases .

- Trace -  The most common recorded information , Generally used for general output 
- Debug -  It's also recording information , But more often than Trace a little bit less , It is usually used to debug programs 
- Info -  Information type messages 
- Warn -  Warning message , It is usually used in important occasions 
- Error -  error message 
- Fatal -  Fatal exception information . In general , After a fatal exception, the program cannot continue to execute .

Log filter : It can be in the routing , Configure custom log filters for each route fliter, As shown below

<rules>
    <logger name="*" writeTo="file">
        <filters>
            <when condition="length('${message}') > 100" action="Ignore" />
            <when condition="equals('${logger}','MyApps.SomeClass')" action="Ignore" />
            <when condition="(level >= LogLevel.Debug and contains('${message}','PleaseDontLogThis'))" action="Ignore" />
            <when condition="not starts-with('${message}','PleaseLogThis')" action="Ignore" />
        </filters>
    </logger>
</rules>

Log filter – Conditional language

Filter expressions are written in a special mini language . The language includes :
Relational operator :==,!=,<,<=,>= and >
Be careful : Some predefined XML Characters may need to be escaped . for example , If you try to use ’<' character , be XML The parser interprets it as a start tag , This will cause errors in the configuration file . It is < In this case, use the escape version of <<(()).
Boolean operator :and,or,not
String text that is always treated as a layout - ${somerenderer}
Boolean - true and false
Numeric text - for example 12345( Integer text ) and 12345.678( Floating point text )
Log level text - LogLevel.Trace,LogLevel.Debug,…LogLevel.Fatal
Predefined keywords to access the most commonly used log event properties - level,message and logger
Curly braces - Override the default priority and grouping expressions together
Conditional function - perform string and object test
A single quotation mark should be escaped with another single quotation mark .

Log filter – Conditional function

contains(s1,s2) Determines whether the second string is a substring of the first . return :true When the second string is a substring of the first string ,false Otherwise return to .
ends-with(s1,s2) Determines whether the second string is a suffix to the first string . return :true When the second string is the prefix of the first string ,false Otherwise return to .
equals(o1,o2) Compare two objects for equality . return :true When two objects are equal ,false Otherwise return to .
length(s) Returns the length of the string .
starts-with(s1,s2) Determines whether the second string is a prefix to the first string . return :true When the second string is the prefix of the first string ,false Otherwise return to .
regex-matches(input, pattern, options) stay NLog 4.5 Introduction in . Indicates whether the regular expression is pattern At the designated input A match was found in the string .options Is an optional comma separated RegexOptions Enumerate the list of values . return :true When a match is found in the input string ,false Otherwise return to

5、 Output to multiple storage media

(1) The configuration file

<?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>
		<!-- Output target :name name f,xsi:type Output type file , fileName Output to the program root directory logs In the folder ,  Generate by date log File name , layout Format of generated content -->
		<target name="f" xsi:type="File" fileName="D:/logs/Nlog/${shortdate}/nlog.log" layout="${longdate} ${uppercase:${level}} ${message}" archiveAboveSize="102400" />
		<!-- Output to console -->
		<target name="c" xsi:type="Console" layout="${longdate} ${uppercase:${level}} ${message}" />
		<!-- Output to csv file -->
		<target name="e" xsi:type="File" fileName="D:/logs/Nlog/${shortdate}/nlog.csv">
			<layout xsi:type="CSVLayout">
				<column name="time" layout="${longdate}" />
				<column name="message" layout="${message}" />
				<column name="logger" layout="${logger}"/>
				<column name="level" layout="${level}"/>
			</layout>
		</target>
	</targets>
	<rules>
		<!-- Log routing rules : The lowest level Debug, Output to target The goal is f-->
		<logger name="*" minlevel="Debug" writeTo="f,c,e" />
	</rules>
</nlog>

(2) Code implementation

Logger Logger = NLog.LogManager.GetCurrentClassLogger();
for (int i = 0; i < 10_000; i++)
{
    Logger.Debug($" I hit Nlog journal !--{i.ToString()}");
}

(3) Running results

If the log file exceeds the set size, new files will be added , In this way, the log file will not be too large to open when you view it later . The number after the name increases from small to large according to the content from morning to night , The file without numbers is always the latest log content .

image-20220620145803220

6、 Output to database

(1)nuget Import assembly

NLog
NLog.Config
NLog.Database   NLog5.0+ Database support must be added separately 
MySql.Data       Database driven 

(2) mount this database , Create databases and tables

mount this database

The installation database can use docker Containerization installation , Simple and easy to use , One line command solution ,docker Relevant knowledge can refer to docker Detailed explanation .

docker run --name mysqlserver -v /data/mysql/conf:/etc/mysql/conf.d -v /data/mysql/logs:/logs -v /data/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 -d -i -p 3306:3306 mysql:latest --lower_case_table_names=1
Parameters explain
–name mysqlserver The name of the container run
-v /data/mysql/conf:/etc/mysql/conf.d The host machine /data/mysql/conf Map to container /etc/mysql/conf.d
-v /data/mysql/logs:/logs The host machine /data/mysql/logs Map to container /logs
-v /data/mysql/data:/var/lib/mysql The host machine /data/mysql/data Map to container /var/lib/mysql
-e MYSQL_ROOT_PASSWORD=123456 Database initial password 123456
-p 3306:3306 The host machine 3306 The port maps to the container 3306 port
–lower_case_table_names=1 Set table names to ignore case , Can only be modified for the first time , It can't be modified later

Create database logmanager

Create table nlog

CREATE TABLE `nlog` (
  `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Application` varchar(50) DEFAULT NULL,
  `Logged` datetime DEFAULT NULL,
  `Level` varchar(50) DEFAULT NULL,
  `Message` varchar(512) DEFAULT NULL,
  `Logger` varchar(250) DEFAULT NULL,
  `Callsite` varchar(512) DEFAULT NULL,
  `Exception` varchar(512) DEFAULT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

(3) The configuration file

<?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" throwExceptions="true" internalLogLevel="Off">
	<targets>
		<!-- Output to database -->
		<target name="d" xsi:type="Database" dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data" connectionString="server= The server IP Address ;Database=logmanager;user id=root;password=123456;SslMode=none">
			<commandText>
				insert into nlog (
				Application, Logged, Level, Message,
				Logger, CallSite, Exception
				) values (
				@Application, @Logged, @Level, @Message,
				@Logger, @Callsite, @Exception
				);
			</commandText>
			<parameter name="@application" layout="MyNlog" />
			<parameter name="@logged" layout="${date}" />
			<parameter name="@level" layout="${level}" />
			<parameter name="@message" layout="${message}" />
			<parameter name="@logger" layout="${logger}" />
			<parameter name="@callSite" layout="${callsite:filename=true}" />
			<parameter name="@exception" layout="${exception:tostring}" />
		</target>
	</targets>
	<rules>		
		<logger name="*" minlevel="Debug" writeTo="d" />
	</rules>
</nlog>

(4) Code implementation

// Create a logging object 
Logger Logger = NLog.LogManager.GetCurrentClassLogger();
// Log out 
Logger.Debug(" I hit Nlog journal !");

(5) Running results

image-20220621145850481

7、 Best practices

(1)NLog.Logger Expected static variable of class

newly build NLog.Logger Objects consume a certain amount of overhead , For example, you need to acquire a lock or allocate an object . Therefore, the following methods are recommended to create NLog.Logger

public class MyClass
{
    
   private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
}

(2) Should be NLog.Logger Format log

Try to avoid formatting directly with strings . for example ,

var message = "Hello" + "Earch";
logger.Info(message);

Recommended NLog.Logger Object to format . for example ,

logger.Info("Hello {0}", "Earth");

NLog.Logger Object can delay the execution of formatting operations , So as to reduce the cost .

(3) The exception object should be passed to NLog.Logger

Avoid using exceptions as parameters for string formatting , Instead, the displayed exception is passed to the function as a parameter . for example ,

try
{
    
}
catch (Exception ex)
{
    
    logger.Error(ex, "Something bad happened");
}

(4) Enable validation of the configuration file

By default ,NLog Shielding all its own exceptions , therefore NLog An error does not crash the application . For most applications , It is suggested that nlog Element addition throwConfigExceptions="true" Property to enable the exception capture function when initializing the configuration , To verify the validity of the configuration file .

<?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" throwConfigExceptions="true">
</nlog>

️ Be careful : There's another one called throwExceptions Properties of , Should not be used in a production environment . It is designed for unit testing and local debugging .

(5) Don't forget Flush Log information

By default ,NLog Automatically when the program is closed flush. Windows limit .NET The application program is closed within a certain time before the program terminates ( It's usually 2 second ). If NLog Of target Network dependent transmission ( for example Http, Mail, Tcp), Then it is recommended to manually execute Flush/Shutdown operation .
Mono/Linux Running on .NET The application needs to be stopped before closing Thread/Timer. If you fail to complete these operations , An unhandled exception is thrown 、 Paragraph errors and other unpredictable behaviors , It is also recommended to manually execute Flush/Shutdown operation .

NLog.LogManager.Shutdown(); // Flush and close down internal threads and timers

8、 Integrated into the Asp.NetCore5 frame

(1)Nuget Import assembly

NLog
NLog.Config
NLog.Web.AspNetCore   Integration Framework 

(2) The configuration file

Put it in a folder CfgFile Unified management , Right click the properties of the configuration file Always copy

<?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" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
	<targets>
		<target xsi:type="File" name="f" fileName="D:/logs/Nlog/${shortdate}/nlog.log" layout="${longdate} ${uppercase:${level}} ${message}" />
	</targets>
	<rules>
		<!--Skip Microsoft logs and so log only own logs-->
		<!-- With Microsoft The leading log will enter this route , Because this route has no writeTo attribute , All will be ignored -->
		<!-- And this route is set final, Therefore, this route will not continue to be matched after it is matched . The unmatched route will continue to match the next route -->
		<logger name="Microsoft.*" minlevel="Trace" final="true" />
		<logger name="*" minlevel="Debug" writeTo="f" />
	</rules>
</nlog>

(3)Program Add pair Nlog Support

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
            .ConfigureLogging(logBuilder =>
            {
                logBuilder.ClearProviders();// Delete all other logging configurations 
                logBuilder.SetMinimumLevel(LogLevel.Trace);// Set the lowest log Level 
                logBuilder.AddNLog("CfgFile/NLog.config");// Support nlog
            });
}

(4) Add controllers and pages , Injection log object

public class FirstController : Controller
{
    private readonly ILogger<FirstController> _ILogger;
    private readonly ILoggerFactory _ILoggerFactory;
    public FirstController(ILogger<FirstController> logger, ILoggerFactory iLoggerFactory)
    {
        this._ILogger = logger;
        _ILogger.LogInformation($"{this.GetType().FullName}  Constructed ....LogInformation");
        _ILogger.LogError($"{this.GetType().FullName}  Constructed ....LogError");
        _ILogger.LogDebug($"{this.GetType().FullName}  Constructed ....LogDebug");
        _ILogger.LogTrace($"{this.GetType().FullName}  Constructed ....LogTrace");
        _ILogger.LogCritical($"{this.GetType().FullName}  Constructed ....LogCritical");

        this._ILoggerFactory = iLoggerFactory;
        ILogger<FirstController> _ILogger2 = _ILoggerFactory.CreateLogger<FirstController>();
        _ILogger2.LogInformation(" This is through Factory Got Logger Write a log ");
    }

    public IActionResult Index()
    {
        _ILogger.LogInformation($"{this.GetType().FullName} Index The requested ");
        return View();
    }
}

(5) Request page , Running results

image-20220621154208469

9、 Integrated into the Asp.NetCore6 frame

(1)Nuget Import assembly

NLog
NLog.Config
NLog.Web.AspNetCore   Integration Framework 

(2) The configuration file

Put it in a folder CfgFile Unified management , Right click the properties of the configuration file Always copy

<?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" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
	<targets>
		<target xsi:type="File" name="f" fileName="D:/logs/Nlog/${shortdate}/nlog.log" layout="${longdate} ${uppercase:${level}} ${message}" />
	</targets>
	<rules>
		<!--Skip Microsoft logs and so log only own logs-->
		<!-- With Microsoft The leading log will enter this route , Because this route has no writeTo attribute , All will be ignored -->
		<!-- And this route is set final, Therefore, this route will not continue to be matched after it is matched . The unmatched route will continue to match the next route -->
		<logger name="Microsoft.*" minlevel="Trace" final="true" />
		<logger name="*" minlevel="Debug" writeTo="f" />
	</rules>
</nlog>

(3)Program Add pair Nlog Support

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // Add services to the container.
        builder.Services.AddControllersWithViews();

        // Configuration log 
        builder.Services.AddLogging(logBuilder =>
        {
            logBuilder.ClearProviders();// Delete all other logging configurations 
            logBuilder.SetMinimumLevel(LogLevel.Trace);// Set the lowest log Level 
            logBuilder.AddNLog("CfgFile/NLog.config");// Support nlog
        });

        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (!app.Environment.IsDevelopment())
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");

        app.Run();
    }
}

(4) Add controllers and pages , Injection log object

public class FirstController : Controller
{
    private readonly ILogger<FirstController> _ILogger;
    private readonly ILoggerFactory _ILoggerFactory;
    public FirstController(ILogger<FirstController> logger, ILoggerFactory iLoggerFactory)
    {
        this._ILogger = logger;
        _ILogger.LogInformation($"{this.GetType().FullName}  Constructed ....LogInformation");
        _ILogger.LogError($"{this.GetType().FullName}  Constructed ....LogError");
        _ILogger.LogDebug($"{this.GetType().FullName}  Constructed ....LogDebug");
        _ILogger.LogTrace($"{this.GetType().FullName}  Constructed ....LogTrace");
        _ILogger.LogCritical($"{this.GetType().FullName}  Constructed ....LogCritical");

        this._ILoggerFactory = iLoggerFactory;
        ILogger<FirstController> _ILogger2 = _ILoggerFactory.CreateLogger<FirstController>();
        _ILogger2.LogInformation(" This is through Factory Got Logger Write a log ");
    }

    public IActionResult Index()
    {
        _ILogger.LogInformation($"{this.GetType().FullName} Index The requested ");
        return View();
    }
}

(5) Request page , Running results

image-20220621154326725

原网站

版权声明
本文为[Brother Li Yu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206232018178547.html