[ASP.NET Core] 透過 NLog 發送訊息到 ElasticSearch
dotnet add package NLog.Web.AspNetCore
dotnet add package NLog.Targets.ElasticSearch
<target name="ElasticSearch"
xsi:type="ElasticSearch"
index="nlog-elk-${date:format=yyyy.MM.dd}"
documentType="logevent"
includeAllProperties="true"
layout="[${date:format=yyyy-MM-dd HH\:mm\:ss}][${level}] ${logger} ${message} ${exception:format=toString}">
<field name="MachineName" layout="${machinename}" />
<field name="ClientIp" layout="${aspnet-request-ip}" />
<field name="TraceId" layout="${aspnet-TraceIdentifier}" />
<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>
<rules>
<logger name="*" minlevel="Info" writeTo="ElasticSearch" />
</rules>
NLog.Extensions.Logging
<target name="ElasticSearch"
xsi:type="ElasticSearch"
url="${configsetting:item=ConnectionStrings.ElasticUrl}"
>
...
</target>
<target name="ElasticSearch"
xsi:type="ElasticSearch"
url="http://127.0.0.1:9200/"
>
...
</target>
public void Configure(IApplicationBuilder app, ILogger<Startup> logger)
{
var logFactory = LogManager.LoadConfiguration("NLog.config");
var target = (ElasticSearchTarget)logFactory.Configuration.FindTargetByName("ElasticSearch");
target.Uri = Configuration["Elastic:Url"];
}
// appsetting.json
"Elastic": {
"Url":"http://127.0.0.1:9200/"
}