Add a NuGet reference
Need to add two NuGet references: NLog.Web.AspNetCore and NLog.Targets.ElasticSearch
Configuration
Add the Nlog.config configuration file and set the property build action to content, copy to output directory to always copy, content as follows.
<?XML version= "1.0" encoding= "Utf-8"?><Nlogxmlns= "Http://www.nlog-project.org/schemas/NLog.xsd"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Internallogtoconsole= "true"> <Extensions> <AddAssembly= "NLog.Targets.ElasticSearch"/> </Extensions> <Targets> <!--Elasticsearch Saving log information - <Targetname= "ElasticSearch"Xsi:type= "ElasticSearch"connectionStringName= "Elasticsearchserveraddress"Index= "userapi-${date:format=yyyy." MM.DD} "DocumentType= "Doc"includeallproperties= "true"Layout= "[${date:format=yyyy-mm-dd hh\:mm\:ss}][${level}] ${logger} ${message} ${exception:format=tostring}"> <Fieldname= "MachineName"Layout= "${machinename}" /> <Fieldname= "Time"Layout= "${longdate}" /> <Fieldname= "Level"Layout= "${level:uppercase=true}" /> <Fieldname= "Logger"Layout= "${logger}" /> <Fieldname= "message"Layout= "${message}" /> <Fieldname= "Exception"Layout= "${exception:format=tostring}" /> <Fieldname= "ProcessID"Layout= "${processid}" /> <Fieldname= "ThreadName"Layout= "${threadname}" /> <Fieldname= "StackTrace"Layout= "${stacktrace}" /> <Fieldname= "Properties"Layout= "${machinename} ${longdate} ${level:uppercase=true} ${logger} ${message} ${exception}|${processid}|${ Stacktrace}|${threadname} " /> </Target> </Targets> <rules> <Loggername="*"MinLevel= "INFO"WriteTo= "ElasticSearch" /> </rules></Nlog>
Modify the Appsettings.json, add the following nodes, note that the debug source only found that the connection must be added to the connectionstrings node, elasticsearchserveraddress node name corresponds to Nlog.config connecti The name of the Onstringname.
"ConnectionStrings": { "elasticsearchserveraddress": "http://192.168.2.97:9200,http:// 192.168.2.101:9200,http://192.168.2.102:9200 "}
Modify Code
To modify the Program.cs file:
Public Static void Main (string[] args) { nlogbuilder.configurenlog ("nlog.config" ); Buildwebhost (args). Run (); publicstatic iwebhost buildwebhost (string[] args) = Webhost.createdefaultbuilder (args) . Usenlog () . Usestartup<Startup>() . Build ();
To modify the Startup.cs file:
Public void Configure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory) { Loggerfactory.addnlog ();}
Test
Public classValuescontroller:controller {PrivateILogger _logger; PublicValuescontroller (ilogger<valuescontroller>logger) {_logger=logger; } [HttpGet] Publicienumerable<string>Get () {_logger. Loginformation ("test it, don't be nervous!"); return New string[] {"value1","value2" }; }}
Kibana query:
. NET core uses Nlog+elasticsearch logging