How to get the Stack trace when logging exceptions with NLog?

后端 未结 4 687
甜味超标
甜味超标 2020-12-23 15:57

When I use the default layout with NLog it only prints the name of the exception. I\'ve been told that the log4jxmlevent layout doesn\'t prints nothing about the exception.

相关标签:
4条回答
  • 2020-12-23 16:46

    As documented in How to Log Exceptions, starting with NLog 4.0, pass the exception as the first parameter to Error, for example like this:

    logger.Error(ex, "Nickers!");
    

    In the NLog configuration (e.g. in web.config or app.config), include ${exception:format=tostring} in the layout, for example like this:

    <target name="f" type="File" layout="${longdate} ${message} ${exception:format=tostring}"/> 
    
    0 讨论(0)
  • 2020-12-23 16:48

    As of NLog 4.5 you can now use:

    logger.Error(exception, message);

    and layout as follows:

    "${longdate} ${level} ${message} ${exception:format=@}"

    The @ means serialize all Exception-properties into Json-format

    0 讨论(0)
  • 2020-12-23 16:51

    I had to use the one of the Logger. + Level + Exception methods:

    logger.ErrorException("ex", ex);
    

    and a custom layout

    layout="${exception:format=ToString,StackTrace}${newline}"
    
    0 讨论(0)
  • 2020-12-23 16:52

    Use the overloads that take an Exception as the second argument:

    catch(Exception crap)
    {
        log.Error("Something went horribly wrong.", crap);
    }
    

    Then in your layout include the ${exception} layout renderer:

    <target ...
        layout="${longdate} ${message} ${exception:format=ToString}" />
    

    Sources:

    • https://github.com/NLog/NLog/wiki/How-to-Log-Exceptions
    • https://github.com/nlog/NLog/wiki/Exception-Layout-Renderer
    0 讨论(0)
提交回复
热议问题