【问题标题】:Adding properties to log message in NLog in .net core在 .net 核心的 NLog 中添加属性以记录消息
【发布时间】:2017-06-16 22:01:59
【问题描述】:

我正在使用NLog 在 .net 核心中记录消息。

我在StartUp.cs中添加了NLog,如下:

loggerFactory.AddNLog();

为了记录到文件,我使用以下方法:

logger.LogInformation("Message");

我想将自定义 NLog 事件属性添加到我的消息中。但是 LogInformation() 不允许我通过它。我该怎么做?

【问题讨论】:

  • 到目前为止的答案并不能真正回答您的问题,是吗?这里的挑战是通过 .NET Core NLog 提供程序将 NLog 事件属性传递给 NLog。如下所示,直接使用 NLog 是一种选择。但这里的前提是使用 ILogger 框架,其中 NLog 是潜在的几个底层提供者之一。顺便说一句,我遇到了同样的挑战,所以,你明白了吗?
  • @BaBu 创建了一个关于如何使用 NLog.Extensions.Logging 版本执行此操作的新答案。 1.0 与 NLog 4.5

标签: asp.net-core .net-core nlog error-logging


【解决方案1】:

NLog 可以与 Microsoft ILogger 集成,并将捕获 messsage-template 属性:

logger.LogInformation("Message {PropertyName}", "PropertyValue");

从 NLog.Extensions.Logging 版本开始支持它。 1.0 结合 NLog 版本。 4.5.

可以在此处找到更多使用 Microsoft ILogger 的高级示例: https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-properties-with-Microsoft-Extension-Logging

请注意,在开发 NetCore 应用程序时,不需要使用 Microsoft ILogger。 NLog 记录器版本。 4.5 在 .NetFramework 和 .NetCore 应用程序上都可以正常工作。另见https://github.com/NLog/NLog/wiki/How-to-use-structured-logging

【讨论】:

  • Tnx! (很抱歉,我无法获得任何替代方案......前两个可能是因为我使用 NLog.Web.AspNetCore,但是为了让 NLog 与 .NET Core 一起工作,我必须这样做,是的? 您的第三个选项,“MyLogEvent”类无法编译。)
  • edit:MyLogEvent 类编译得很好,我是个白痴。但是 {$event-properties} 渲染器仍然没有选择虚幻的属性。
  • 关于版本:我正在使用 NLog.Web.AspNetCore (4.4.1),它似乎包括 NLog (5.0.0-beta07) 和 NLog.Extensions.Logging (1.0.0-rtm- β5)。所以,我应该没事。但这行不通。
  • 我知道这很令人困惑,但 NLog 5.0 BETA 已经过时并且仅对 UWP10 应用程序有用。最新版本是 NLog 4.5 RC
  • NLog.Web.AspNetCore 依赖于 NLog.Extensions.Logging,并添加了一些在创建 Asp.NetCore 应用程序时有用的额外布局渲染。当使用 NLog.Web.AspNetCore 4.5.0 时,它将打开对上述 wiki 页面中描述的新内容的访问。
【解决方案2】:

查找在您的 .NET 应用程序中设置 Nlog 的分步信息。

第 1 步:- 安装

从 Nuget Manager 安装 NLog 和 NLog.Extended 版本 4.0.0.0。

第 2 步:- WebConfig 配置

    <configSections>
        <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
    </configSections>
    
    <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" throwExceptions="false" internalLogFile="D:\NLogErrors\log.txt">
        <extensions>
          <!-- load NLog.Extended to enable ASP.NET-specific functionality -->
          <add assembly="NLog.Extended" />
        </extensions>
        <!--Define Various Log Targets like files, database or asp.net trace files-->
        <targets>
          <target name="oracle" xsi:type="Database" keepConnection="false" dbProvider="Oracle.DataAccess.Client.OracleConnection, Oracle.DataAccess, Version=4.121.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" connectionString="Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = "" )(PORT = 1521))(CONNECT_DATA =(SID = "")));User Id="";Password="";" commandText="INSERT INTO LOGTABLE (LOGMESSAGE,LOGLEVEL,LOGGERNAME,CREATEDDATETIME,SESSIONID,BROWSERDETAIL,REQUESTURL,ERRORMESSAGE,PRODUCERCODE,QUOTENO,CUSTOMER_IP_ADDRESS,SERVER_IP_ADDRESS) values(:LOGMESSAGE,:LOGLEVEL,:LOGGERNAME,:CREATEDDATETIME,:SESSIONID,:BROWSERDETAIL,:REQUESTURL,:ERRORMESSAGE,:PRODUCERCODE,:QUOTENO,:CUSTOMER_IP_ADDRESS,:SERVER_IP_ADDRESS)">
            <parameter name="LOGMESSAGE" layout="${message}" />
            <parameter name="LOGLEVEL" layout="${level:uppercase=true}" />
            <parameter name="LOGGERNAME" layout="${logger}" />
            <parameter name="CREATEDDATETIME" layout="${date}" />
            <parameter name="SESSIONID" layout="${event-context:item=SessionId}" />
            <parameter name="BROWSERDETAIL" layout="${event-context:item=BrowserDetail}" />
            <parameter name="REQUESTURL" layout="${event-context:item=RequestUrl}" />
            <parameter name="ERRORMESSAGE" layout="${event-context:item=ErrorMessage}" />
            <parameter name="PRODUCERCODE" layout="${event-context:item=ProducerCode}" />
            <parameter name="QUOTENO" layout="${event-context:item=QuoteNo}" />
            <parameter name="CUSTOMER_IP_ADDRESS" layout="${event-context:item=CUSTOMER_IP_ADDRESS}"/>
            <parameter name="SERVER_IP_ADDRESS" layout="${event-context:item=SERVER_IP_ADDRESS}"/>
          </target>
          <target xsi:type="Mail" name="Email" html="true" addNewLines="false" replaceNewlineWithBrTagInHtml="false" subject="Error Log" to="xyz@gmail.com" useSystemNetMailSettings="true" body="${event-context:item=EmailBody}">
          </target>
        </targets>
        <rules>
          <logger name="*" minlevel="trace" writeTo="oracle" />
          
        </rules>
      </nlog>

第 3 步:- Cs 代码

    public static class NLogManager
        {
            public static ILogger _logger = 
             NLog.LogManager.GetCurrentClassLogger();
    
            public static void InfoLog(NLogData nLogData)
            {
                LogEventInfo theEvent = new LogEventInfo(LogLevel.Info, NLogManager._logger.Name, nLogData.Message);
                SetLogEventInfo(theEvent, nLogData);
                _logger.Log(theEvent);
            }
    }
    
     private static void SetLogEventInfo(LogEventInfo theEvent, NLogData 
         nLogData)
            {
                theEvent.Properties["SessionId"] = nLogData.SessionId;
                theEvent.Properties["BrowserDetail"] = nLogData.BrowserDetail;
                theEvent.Properties["RequestUrl"] = nLogData.RequestUrl;
                theEvent.Properties["ErrorMessage"] = nLogData.ErrorMessage;
                theEvent.Properties["EmailBody"] = nLogData.EmailBody;
                theEvent.Properties["ProducerCode"] = nLogData.ProducerCode;
                theEvent.Properties["QuoteNo"] = nLogData.QuoteNo;
                theEvent.Properties["CUSTOMER_IP_ADDRESS"] = nLogData.CustomerIPAddress;
                theEvent.Properties["SERVER_IP_ADDRESS"] = nLogData.ServerIPAddress;
            }

第 4 步:- 模型实体


    public class NLogData
        {
            public string SessionId { get; set; }
    
            public string Message { get; set; }
    
            public string RequestUrl { get; set; }
    
            public string BrowserDetail { get; set; }
    
            public string Method { get; set; }
    
            public string ErrorMessage { get; set; }
    
            public string EmailBody { get; set; }
    
            public string ProducerCode { get; set; }
    
            public string QuoteNo { get; set; }
    
            public string CustomerIPAddress { get; set; }
    
            public string ServerIPAddress { get; set; }
        }

第 5 步:- 在您实施日志记录的位置添加以下行


     NLogManager.TraceLog(NLogData nlogData);

-- 创建上述方法接受的正确格式并相应设置值

如果您有任何疑问,请留下评论或发送邮件至 ankitmori14@gmail.com

【讨论】:

    【解决方案3】:

    如果您想要自定义布局属性(NLog 称它们为布局渲染器),您可以使用EventProperties Layout Renderer。您可以在代码中简单地执行此操作:

    var logger = LogManager.GetCurrentClassLogger();
    var eventInfo = new LogEventInfo(LogLevel.Info, logger.Name, "Message");
    eventInfo.Properties["CustomValue"] = "My custom string";
    eventInfo.Properties["CustomDateTimeValue"] = new DateTime(2020, 10, 30, 11, 26, 50);
    // You can also add them like this:
    eventInfo.Properties.Add("CustomNumber", 42);
    // Send to Log
    logger.Log(eventInfo);
    

    然后您将能够在您的 nlog.config 中添加这些(您制作的任何属性)

    <target>
      <parameter name="@customtime" layout="${event-properties:CustomDateTimeValue:format=yyyy-MM-dd HH\:mm\:ss}" />
      <parameter name="@customvalue" layout="${event-properties:item=CustomValue}" />
      <parameter name="@customnumber" layout="${event-properties:item=CustomNumber}" />
    </target>
    

    在将 NLog 与 AspNetCore 一起使用时,添加 NLog.Web Package for ASP.NET Core 很有用,它为您提供了许多预定义的布局渲染器。你可以在他们的 Github 页面上找到更多关于 NLog.Web for AspNetCore 的信息。

    此 AspNetCore 包将为您提供如下内容:

    <parameter name="@UserName" layout="${aspnet-user-identity}" />
    <parameter name="@MvcAction" layout="${aspnet-MVC-Action}" />
    <parameter name="@Session" layout="${aspnet-session:Variable=User.Name:EvaluateAsNestedProperties=true}" />
    ... etc
    

    您可以在NLog.Web.AspNetCore Github page 上找到完整列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 2017-04-23
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      相关资源
      最近更新 更多