An overview of the
Elasticsearch is widely used in log analysis, full-text search, structured data analysis, and other scenarios, reducing the cost of maintaining multiple dedicated systems. It is very popular in the open source community. If logs are output as files in the system, it is inconvenient to view system logs. If you save logs to a database, you cannot perform full-text search. Here we export the log to ElasticSearch and use Kibana to find the log.
implementation
1. Configure the ES service address
{
"ConnectionStrings": {
"ElasticSearchServerAddress": "http://localhost:9200"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
Copy the code
2. Configure nlog.config
<? The 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" internalLogToConsole="true"> <extensions> <add assembly="NLog.Targets.ElasticSearch"/> </extensions> <targets> <! --> <target name="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}"> <field name="MachineName" layout="${machinename}" /> <field name="Time" layout="${longdate}" /> <field name="level" layout="${level:uppercase=true}" /> <field name="logger" layout=" ${logger}" /> <field name="message" layout=" ${message}" /> <field name="exception" layout=" ${exception:format=toString}" /> <field name="processid" layout=" ${processid}" /> <field name="threadname" layout=" ${threadname}" /> <field name="stacktrace" layout=" ${stacktrace}" /> <field name="Properties" layout="${machinename} ${longdate} ${level:uppercase=true} ${logger} ${message} ${exception}|${processid}|${stacktrace}|${threadname}" /> </target> </targets> <rules> <logger name="*" minlevel="INFO" writeTo="ElasticSearch" /> </rules> </nlog>Copy the code
3. Test write to log
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
var result = new string[] { "value1", "value2" };
_logger.LogInformation(JsonConvert.SerializeObject(result));
return result;
}
Copy the code