.net core使用NLog+Elasticsearch记录日志

时间:2022-08-24 14:20:59

在微服务或分布式系统中,如果将日志作为文件输出,查看系统日志将非常不便;如果将日志保存到数据库中,又不能进行全文搜索。在这里我们将日志输出到ElasticSearch中,借助Kibana再查找日志。

添加Nuget引用

需要添加两个Nuget引用:NLog.Web.AspNetCore和NLog.Targets.ElasticSearch

配置

新增nlog.config配置文件,并设置属性生成操作为内容,复制到输出目录为始终复制,内容如下。

<?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>
<!--ElasticSearch保存日志信息-->
<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>

修改appsettings.json,增加如下节点,注意,经调试源码才发现,这里必须将连接增加到ConnectionStrings节点下,ElasticSearchServerAddress节点名称对应nlog.config中ConnectionStringName的名称。

"ConnectionStrings": {
"ElasticSearchServerAddress": "http://192.168.2.97:9200,http://192.168.2.101:9200,http://192.168.2.102:9200"
}

修改代码

修改Program.cs文件:

public static void Main(string[] args)
{
NLogBuilder.ConfigureNLog("nlog.config");
BuildWebHost(args).Run();
} public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseNLog()
.UseStartup<Startup>()
.Build();

  修改Startup.cs文件:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddNLog();
}

测试

    public class ValuesController : Controller
{
private ILogger _logger; public ValuesController(ILogger<ValuesController> logger)
{
_logger = logger;
} [HttpGet]
public IEnumerable<string> Get()
{
_logger.LogInformation("测试一下,不要紧张!");
return new string[] { "value1", "value2" };
}
}

kibana里查询截图:.net core使用NLog+Elasticsearch记录日志