I'm using NLog to send emails when an exception occurs in my app. Here's a portion of my target :
<target xsi:type="Mail"
name="email"
subject="${level}:" .. >
I receive emails with subjects like "Error:" or "Fatal:". This works fine but I want to add the Exception.Message to the subject of the email
Is it possible to setup custom properties in NLog. I can't find out how to do this, so just to make it clear what I want here is an example of the kind of thing I'm trying to do :
m_oLogger.Fatal( oException.BuildMessage(), new {MyMessage=oException.Message});
*Note that BuildMessage() is just an extension method to convert the full exception details (including inner exceptions) to a readable string
And in my target :
<target xsi:type="Mail"
name="email"
subject="${level}: ${Custom.MyMessage}" .. >
Then I would get emails with the subjects like :
Fatal: Syntax error in parameters or arguments. The server response was: Account does not exist
Is this kind of flexibility possible with NLog? If not, do you know of another .NET logging platforms that offers this kind of functionality?
In general instead of creating custom layoutRenderer suggested by wageoghe it's possible to use EventContext-Layout-Renderer that allows 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 your NLog.config file:
${event-context:item=MyValue} -- renders "My custom string
For the particular https://github.com/nlog/NLog/wiki/Exception-Layout-Renderer the format should be
${exception:format=message}
It is very easy to add a custom LayoutRenderer to NLog. See my first answer to this question for an example of a LayoutRenderer that allows you to add the System.Diagnostics.Trace.CorrelationManager.ActivityId value to your logging output.
To do what you want, you probably don't need a custom LayoutRenderer. If you want to send an email whose subject is the log leve PLUS the Message property of the exception, you should be able to configure something like this:
<target xsi:type="Mail"
name="email"
subject="${level}: ${exception.Message}" ..>
That should create the subject of the email by concatenating the level and the value of the Exception.Message property. You will have to call the logging overload that takes an Exception as a parameter.
Does this help?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With