logging exception in c#

前端 未结 6 1321
轮回少年
轮回少年 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:44

    I am only answering for the ask, other people have already mentioned about the code already. If you want the line number to be included in your log you need to include the generated debug files (pdb) in your deployment to the server. If its just your Dev/Test region that is fine but I don't recommend using in production.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-29 05:49

    Also, when you deploy a release build of your code to a production environment for instance, don't forget to include the .pdb files in the release package. You need that file to get the line number of the code that excepted (see How much information do pdb files contain? (C# / .NET))

    0 讨论(0)
  • 2020-12-29 05:49

    Please note that the exception class is serializable. This means that you could easily write the exception class to disk using the builtin XmlSerializer - or use a custom serializer to write to a txt file for example.

    Logging to output can ofcourse be done by using ToString() instead of only reading the error message as mentioned in other answers.

    Exception class

    https://docs.microsoft.com/en-us/dotnet/api/system.exception?redirectedfrom=MSDN&view=netframework-4.7.2

    Info about serialization, the act of converting an object to a file on disk and vice versa.

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/

    0 讨论(0)
  • 2020-12-29 05:57

    Just log ToString(). Not only will it give you the stack trace, but it'll also include the inner exceptions.

    0 讨论(0)
  • 2020-12-29 05:59

    I find that the easiest way to log exceptions in C# is to call the ToString() method:

    try
    {
    
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
    

    This usually gives you all the information you need such as the error message and the stack trace, plus any extra exception specific context information. (however note that the stack trace will only show you source files and line numbers if you have your application compiled with debug information)

    It is worth noting however that seeing a full stack trace can be fairly offputting for the user and so wherever possible you should try to handle exceptions and print out a more friendly error message.

    On another note - you should replace your method WriteLogError with a fully featured logging framework (like Serilog) instead of trying to write your own.

    Your logging method is not thread safe (your log file will probably end up with log messages being intermingled with each other) and also should definitely not call itself if you catch an exception - this will mean that any exceptions that occur whilst logging errors will probably cause a difficult to diagnose StackOverflow exception.

    I could suggest how to fix those things, however you would be much better served just using a proper logging framework.

    0 讨论(0)
提交回复
热议问题