NLog 通过http保存日志

简介

NLog是一个基于.NET平台编写的类库,我们可以使用NLog在应用程序中添加极为完善的跟踪调试代码。 NLog是一个简单灵活的.NET日志记录类库。通过使用NLog,我们可以在任何一种.NET语言中输出带有上下文的(contextual information)调试诊断信息,根据喜好配置其表现样式之后发送到一个或多个输出目标(target)中。

NLog的API非常类似于log4net,且配置方式非常简单。NLog使用路由表(routing table)进行配置,但log4net却使用层次性的appender配置,这样就让NLog的配置文件非常容易阅读,并便于今后维护。 NLog遵从BSD license,即允许商业应用且完全开放源代码。任何人都可以免费使用并对其进行测试,然后通过邮件列表反馈问题以及建议。.

NLog支持.NET、C/C++以及COM interop API,因此我们的程序、组件、包括用C++/COM 编写的遗留模块都可以通过同一个路由引擎将信息发送至NLog中。

代码实现

1、自定义变量

<variable name="accessToken" value="UKncvUQRoPWx8lCvwED105GoWYikIGrOPzGpJOMQMCB" />
 <variable name="notifyApiUrl" value="http://localhost:8088/LogCollection" />
 <variable name="typesite" value="YuanFeng.LegalDoc.Api" />


2、配置输出

 <target type="WebService" encoding="utf-8" name="lineNotify" url="${notifyApiUrl}" protocol="HttpPost">
   <parameter name="accessToken" type="System.String" layout="${accessToken}" />
   <parameter name="localip" type="System.String" layout="${local-ip}" />
   <parameter name="level" type="System.String" layout="${level}" />
   <parameter name="typesite" type="System.String" layout="${typesite}" />
   <parameter name="message" type="System.String" layout="YuanFeng.LegalDoc.Api - ${local-ip}|${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
  </target>

3、新建log项目,接收日志

  [HttpPost]
        public bool Post([FromForm] Logarg request)
        {
            if (request.accessToken != "UKncvUQRoPWx8lCvwED105GoWYikIGrOPzGpJOMQMCB")
            {
                return false;
            }

            if (request.level == "Error")
                logger.LogError(request.message + "{localipstr} {typesite}", request.localip, request.typesite);
            if (request.level == "Info")
                logger.LogInformation(request.message + "{localipstr} {typesite}", request.localip, request.typesite);
            return true;
        }

4、输出日志到文件

<?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

 <variable name="myvar" value="myvalue" />
 <targets>
  <target xsi:type="File" name="f" fileName="${basedir}/logs/${event-properties:item=localipstr}/${event-properties:item=typesite}/${shortdate}/${level}.log"
     layout="${longdate} ${uppercase:${level}} ${message}"
    maxArchiveFiles="999"
     archiveAboveSize="10485760" />
 </targets>
 <rules>
  <logger name="*" minlevel="Info" writeTo="f" />
 </rules>
</nlog>