ElasticSearch+NLog实现.net core分布式日志管理

概述

 Elasticsearch可广泛应用于日志分析、全文检索、结构化数据分析等多种场景,大幅度降低维护多套专用系统的成本,在开源社区非常受欢迎。在系统中,如果将日志作为文件输出,查看系统日志将非常不便;如果将日志保存到数据库中,又不能进行全文搜索。在这里我们将日志输出到ElasticSearch中,借助Kibana再查找日志。

实现方式

1、配置es服务地址

 

{
  "ConnectionStrings": {
    "ElasticSearchServerAddress": "http://localhost:9200"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

 

2、配置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>

 

3、测试写入日志

 

 // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            var result = new string[] { "value1", "value2" };
            _logger.LogInformation(JsonConvert.SerializeObject(result));
            return result;
        }

 

效果

ElasticSearch+NLog实现.net core分布式日志管理

 

上一篇:asp.net core 使用nlog记录日志


下一篇:docker部署Exceptionless(.net core3.1版本)-随笔