Adding properties to log message in NLog in .net core

后端 未结 3 1317
难免孤独
难免孤独 2020-12-11 05:53

I am using NLog for logging messages in .net core.

I have added NLog in StartUp.cs as follows:



        
3条回答
  •  青春惊慌失措
    2020-12-11 06:16

    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

    
      
      
      
    
    

    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:

    
    
    
    ... etc
    

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

提交回复
热议问题