前言:
眼前姐妹们对“net core nlog”大概比较注重,姐妹们都需要剖析一些“net core nlog”的相关文章。那么小编在网络上搜集了一些有关“net core nlog””的相关知识,希望看官们能喜欢,姐妹们快快来了解一下吧!上一篇文章asp.net core 5.0使用nlog介绍了asp.net core 5.0中nlog的基本使用和多环境的支持,现在来介绍一下如何使用nlog将日志输出到ElasticSearch。
这里有有心的小伙伴已经封装好了一个Nuget包NLog.Targets.ElasticSearch,我们直接使用即可。
第一步:安装Nuget包,目前最新稳定版是7.6.0
Install-Package NLog.Targets.ElasticSearch 7.6.0
第二步:在配置文件中做如下修改
在extensions节点中添加子节点<add assembly="NLog.Targets.ElasticSearch"/>在targets节点中添加名称为elastic的子节点target在rules节点中添加子节点logger,并指定writeTo为elastic
<?xml version="1.0" encoding="utf-8"?><nlog xmlns="; xmlns:xsi="; autoReload="true" internalLogToConsole="false" > <extensions> <add assembly="NLog.Web.AspNetCore"/> <add assembly="NLog.Targets.ElasticSearch"/> </extensions> <variable name="logLayout" value="Logger:${logger}${newline}Date:${longdate} Level:${uppercase:${level}}${newline}Message:${message} ${newline}${onexception:Exception:${exception:format=toString}${newline}}" /> <targets> <!--ElasticSearch--> <target name="elastic" xsi:type="ElasticSearch" uri="; index="projectName-${environment:variable=ASPNETCORE_ENVIRONMENT}-${level}" documentType="_doc" includeAllProperties="true"> <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}" /> </target> <!--Console--> <target xsi:type="Console" name="logToConsole" layout="${logLayout}" /> </targets> <rules> <logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="logToConsole" final="true" /> <logger name="System.Net.Http.*" maxlevel="Info" final="true" /> <logger name="Microsoft.*" maxlevel="Info" final="true" /> <logger name="*" minlevel="Info" writeTo="elastic" /> </rules></nlog>
第三步:启动程序,构造注入ILogger进行日志记录
public class WeatherForecastController : ControllerBase{ private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; }
这样我们就能把日志输出到ElasticSearch了,是不是很简单呢
标签: #net core nlog