logging exception in c#

前端 未结 6 1322
轮回少年
轮回少年 2020-12-29 04:52

logging exception the code below allows to save the content of an exception in a text file. Here I\'m getting only the decription of the error.

6条回答
  •  天涯浪人
    2020-12-29 05:47

    Your solution is pretty good. I went through the same phase
    and eventually needed to log more and more (it will come...):

    • logging source location
    • callstack before exception (could be in really different place)
    • all internal exceptions in the same way
    • process id / thread id
    • time (or request ticks)
    • for web - url, http headers, client ip, cookies, web session content
    • some other critical variable values
    • loaded assemblies in memory
    • ...

    Preferably in the way that I clicked on the file link where the error occurred,
    or clicked on a link in the callstack, and Visual Studio opened up at the appropriate location.
    (Of course, all you need to do is *.PDB files, where the paths from the IL code
    to your released source in C # are stored.)

    So I finally started using this solution:
    It exists as a Nuget package - Desharp.
    It's for both application types - web and desktop.
    See it's Desharp Github documentation. It has many configuration options.

    try {
        var myStrangeObj = new { /*... something really mysterious ...*/ };
        throw new Exception("Something really baaaaad with my strange object :-)");
    } catch (Exception ex) {
    
        // store any rendered object in debug.html or debug.log file
        Desharp.Debug.Log(myStrangeObj, Desharp.Level.DEBUG);
    
        // store exception with all inner exceptions and everything else
        // you need to know later in exceptions.html or exceptions.log file
        Desharp.Debug.Log(ex);
    }
    

    It has HTML log formats, every exception in one line,
    and from html page you can open in browser, you can click
    on file link and go to Visual Studio - it's really addictive!
    It's only necessary to install this Desharp editor opener.

    See some demos here:

    • Web Basic App
    • Web MVC App
    • Console App

    Try to check out any of those repos and log something by the way above.
    then you can see logged results into ~/Logs directory. Mostly anything is configurable.

提交回复
热议问题