.Net Core 使用Nlog 记录日志

2019-04-04  本文已影响0人  JADDC
一、使用Nlog将日志记录到TXT文本中

参考:https://www.cnblogs.com/qmhuang/p/8305915.html

使用说明
二、使用Nlog将日志记录到sql server数据库
新建完Nlog文件,配置其属性
        <?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="Warn"
            internalLogFile="Logs/nlog-internal.log">

        <!--internalLogLevel="Off"-->
        <!-- optional, add some variables
        https://github.com/nlog/NLog/wiki/Configuration-file#variables
        -->
        <variable name="myvar" value="myvalue"/>

        <!--
        See https://github.com/nlog/nlog/wiki/Configuration-file
        for information on customizing logging rules and outputs.
         -->
        <targets>

          <!--
          add your targets here
          See https://github.com/nlog/NLog/wiki/Targets for possible targets.
          See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
          -->

          <!--
          Write events to a file with the date in the filename.
          <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
                  layout="${longdate} ${uppercase:${level}} ${message}" />
          -->

          <!-- write logs to file -->
          <target xsi:type="File" name="allfile" fileName="Logs/${date:format=yyyyMM}/nlog-all-${shortdate}.log"
                   layout="${longdate}|${event-properties:item=EventId.Id}|${uppercase:${level}}|${logger} ${newline}${message} ${exception} ${newline}" />

          <target xsi:type="File" name="ownFile-web" fileName="Logs/${date:format=yyyyMM}/nlog-own-${shortdate}.log"
                   layout="${longdate}|${event-properties:item=EventId.Id}|${uppercase:${level}}|${logger} ${newline}${message} ${exception} ${newline} --- |url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />

          <target xsi:type="Null" name="blackhole" />

          <target xsi:type="Database" name="error">
            <connectionString>${var:connectionString}</connectionString>
            <commandText>
              INSERT INTO [dbo].[Error]
              ([Application]
              ,[Level]
              ,[Logger]
              ,[Callsite]
              ,[RequestHeaders]
              ,[RequestBody]
              ,[RequestURL]
              ,[Response]
              ,[Referrerurl]
              ,[Action]
              ,[Message]
              ,[Exception]
              ,[Operatingtime]
              ,[ServerAddress]
              ,[RemoteAddress])
              VALUES
              (@application
              ,@levels
              ,@logger
              ,@callSite
              ,@requestHeaders
              ,@requestBody
              ,@requestURL
              ,@response
              ,@referrerurl
              ,@action
              ,@message
              ,@exception
              ,@operatingtime
              ,@serverAddress
              ,@remoteAddress);
            </commandText>
            <parameter name="@application" layout="BackendAPI" />
            <parameter name="@levels" layout="${level}" />
            <parameter name="@logger" layout="${logger}" />
            <parameter name="@callSite" layout="${callsite}" />
            <parameter name="@requestHeaders" layout="Null" />
            <parameter name="@requestBody" layout="${event-context:item=requestBody}" />
            <parameter name="@requesturl" layout="${aspnet-request-url}" />
            <parameter name="@response" layout="${event-context:item=response}" />
            <parameter name="@referrerurl" layout="${aspnet-request}" />
            <parameter name="@action" layout="${aspnet-mvc-action}" />
            <parameter name="@message" layout="${event-context:item=message}" />
            <parameter name="@exception" layout="${event-context:item=exception}" />
            <!--<parameter name="@exception" layout="${exception:tostring}" />-->
            <parameter name="@operatingTime" layout="${date}" />
            <parameter name="@serverAddress" layout="${machinename}" />
            <parameter name="@remoteAddress" layout="${aspnet-Request-IP}" />
          </target>


        </targets>

        <rules>
          <!-- add your logging rules here -->

          <!--
          Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
          <logger name="*" minlevel="Debug" writeTo="f" />
          -->

          <!--All logs, including from Microsoft-->
          <!--minlevel 改为Trace 跟踪全部 Error 只捕获异常-->
          <logger name="*" minlevel="Error" writeTo="allfile" />

          <!--Skip Microsoft logs and so log only own logs-->
          <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
          <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
          <logger name="*" minlevel="Error" writeTo="error" />


        </rules>
      </nlog>

全部配置如下图:


全局配置Nlog

appsettings.json文件内容如下:

  {
    "ConnectionStrings": {
      "Test": "Server=.; Initial Catalog=TestDB; Persist Security Info=True; User ID=**; Password=***;"
    },
    "Logging": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "AllowedHosts": "*"
  }

方法一:

private readonly Logger _logger = LogManager.GetCurrentClassLogger();
var logEventInfo = new LogEventInfo() { };
        logEventInfo.Properties["requestBody"] = "requestBody";
        logEventInfo.Properties["exception"] = "exception";
        logEventInfo.Properties["message"] = "context.Exception.Message";
        logEventInfo.Properties["response"] = "response.ToJSON()";

        _logger.Log(LogLevel.Error, logEventInfo);

方法二:

        NLog.Logger logger = LogManager.GetCurrentClassLogger();

        var logEventInfo = new LogEventInfo() { };
        logEventInfo.Properties["requestBody"] = "requestBody";
        logEventInfo.Properties["exception"] = "exception";
        logEventInfo.Properties["message"] = "context.Exception.Message";
        logEventInfo.Properties["response"] = "response.ToJSON()";

        //_logger.Log(LogLevel.Error, logEventInfo);
         logger.Log(LogLevel.Error, logEventInfo);
三、其他

LogCritical,用来记录严重的事情
LogDebug,记录调试信息
LogError,记录异常
LogInformation,记录信息性的事情
LogTrace,记录追踪信息
LogWarning,记录警告信息

下面是ASP.NET Core里面定义的LogLevel(它是个枚举), 按严重性从低到高排序的:

Trace = 0, 它可以包含敏感拘束, 默认在生产环境中它是被禁用掉的.

Debug = 1, 也是在调试使用, 应该在生产环境中禁用, 但是遇到问题需要调试可以临时启用.

Information = 2, 用来追踪应用程序的总体流程.

Warning = 3, 通常用于记录非正常或意外的事件, 也可以包括不会导致应用程序停止的错误和其他事件, 例如验证错误等.

Error = 4, 用于记录无法处理的错误和异常, 这些信息意味着当前的活动或操作发生了错误, 但不是应用程序级别的错误.

Critical = 5, 用于记录需要立即处理的事件, 例如数据丢失或磁盘空间不足.

None = 6, 如果你不想输出日志, 你可以把程序的最低日志级别设置为None, 此外还可以用来过滤日志.

非常有用的学习例子:https://www.cnblogs.com/bijinshan/p/9140111.html

上一篇下一篇

猜你喜欢

热点阅读