Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nlog output characters if exception not null

Tags:

c#

asp.net

nlog

Is there a way in Nlog to output certain character only if Exception is not null. For example my layout is:

layout="${longdate}|${callsite:skipFrames=1}|${message}|${exception:format=tostring}" 

If I call NLog.Debug("Hello") the output will be:

2015-12-07 11:50:00.5114|MyDll.MyClass.MyMethod|Hello|

That last character | is being printed out. Is there a way to prevent this, and only print it out if there is an actual exception being printed?

like image 672
Bagzli Avatar asked Dec 07 '15 17:12

Bagzli


3 Answers

You can use the ${onexception:INNER} layout renderer for this.

${message}${onexception:|${exception:format=Type,Message,StackTrace,Data}}

If there is an exception, it will prepend a '|' followed by whatever you specifiy as your exception format. If no exception is present, only the ${message} will be rendered.

like image 118
Alex Avatar answered Oct 21 '22 20:10

Alex


Also look at "When" Layout Renderer

${when:when=Condition:inner=Layout} 

EDIT by OP to show working solution for future visitors:

layout="${longdate}|${callsite:skipFrames=1}|${message}${when:when=length('${exception}')>0:Inner=|}${exception:format=tostring}"
like image 17
skalinkin Avatar answered Oct 21 '22 19:10

skalinkin


I've been using the exceptionSeparator parameter of $(message), this is only output if there is an exception. Eg. to give a space between message an exception:

<variable name="StdLayout" 
value="${longdate} | ${level} | ${logger} | ${message:exceptionSeparator= }${exception:format=tostring}" />
like image 3
Richard Avatar answered Oct 21 '22 19:10

Richard