Adding properties to log message in NLog in .net core

混江龙づ霸主 提交于 2019-11-29 10:45:49
truemedia

If you want custom layout properties (NLog calls them layout renderers) you can use the EventProperties Layout Renderer. You can simply do this in your code:

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);

Then you will be able to add these (any any properties you make up) in your 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>

When using NLog with AspNetCore, it's useful to add the NLog.Web Package for ASP.NET Core which gives you many predefined Layout renderers. You can find more about NLog.Web for AspNetCore on their Github page.

This AspNetCore package will give you things like the following:

<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

You will find the complete list on the NLog.Web.AspNetCore Github page.

Created a Wiki page just for you:

https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-properties-with-Microsoft-Extension-Logging

Requires NLog.Extensions.Logging ver. 1.0 with NLog ver. 4.5

Find step by step information to setup Nlog in your .NET Application.

Step 1:- Installation

Install NLog and NLog.Extended of version 4.0.0.0 from Nuget Manager.

Step 2:- WebConfig configuration

<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>

Step 3:- Cs Code

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;
        }

Step 4:- Model Entity

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; }
    }

Step 5 :- Add Below line from where you have implement logging

 NLogManager.TraceLog(NLogData  nlogData);

-- Create proper format which is accepted by above method and set value accordingly

If you have any query please leave comment or mail me on ankitmori14@gmail.com

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!