How flexible is NLog? I want custom layout properties

I use NLog to send emails when an exception occurs in my application. Here is part of my goal:

<target xsi:type="Mail" name="email" subject="${level}:" .. > 

I get emails with topics such as "Error:" or "Fatal:". This works fine, but I want to add Exception.Message to the subject line

Is it possible to configure custom properties in NLog. I cannot figure out how to do this, so just to understand what I want here is an example of what I'm trying to do:

 m_oLogger.Fatal( oException.BuildMessage(), new {MyMessage=oException.Message}); 

* Note: BuildMessage () is just an extension method for converting all the details of an exception (including internal exceptions) to a readable string

And for my purpose:

 <target xsi:type="Mail" name="email" subject="${level}: ${Custom.MyMessage}" .. > 

Then I would receive emails with topics such as:

Fatal: Syntax error in parameters or arguments. Server response: Account does not exist

Is such flexibility possible in NLog? If not, do you know about other .NET registration platforms that offer such functionality?

+4
source share
3 answers

It is very easy to add a custom LayoutRenderer to NLog. See my first answer to this question for an example LayoutRenderer that allows you to add a System.Diagnostics.Trace.CorrelationManager.ActivityId value to your log.

To do what you want, you probably don't need a custom LayoutRenderer. If you want to send an email whose subject is the PLUS log list, the Message property to exclude, you should be able to configure something like this:

 <target xsi:type="Mail" name="email" subject="${level}: ${exception.Message}" ..> 

This should create a subject line by combining the level and value of the Exception.Message property. You will need to cause a log overload that takes an exception as a parameter.

Does it help?

+5
source

In general, instead of creating a custom layoutRenderer proposed by wageoghe , you can use EventContext-Layout-Renderer , which allows you to pass any number of custom properties

 LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, "", "Pass my custom value"); theEvent.Properties["MyValue"] = "My custom string";` log.Log(theEvent); 

and in the NLog.config file:

 ${event-context:item=MyValue} -- renders "My custom string 

For a specific https://github.com/nlog/NLog/wiki/Exception-Layout-Renderer format should be

  ${exception:format=message} 
+5
source

This is probably impractical: I am sure that the NLog structure is not reflected as part of its logging format [this requires that NLog has some kind of concept of where your reference assemblies are and what type they are.]

Can you just do all the parsing / formatting of messages in C # code and pass it as part of existing variables? They list many of them in the "Mail Subscription" NLog documenation .

0
source

Source: https://habr.com/ru/post/1340434/


All Articles