开发者

Exception capturing and Error logging

开发者 https://www.devze.com 2023-04-07 16:36 出处:网络
I have got a utility class, called ErrorLog, which basically does some basic error logging kinda stuff, recording error messages, stacktraces, etc.

I have got a utility class, called ErrorLog, which basically does some basic error logging kinda stuff, recording error messages, stacktraces, etc.

So in my main c# app, I almost always chuck this piece of code, ErrorLog el = new ErrorLog() into the catch(Exception e) part, and then start calling its methods to do logging.

For example, here is 1 of the methods in ErrorLog class

public void logErrorTraceToFile(string fname, string errorMsg, string errorStackTrace)
{ 
    //code here
}

Anyway, I am just wondering if it's a good approach to log errors in this wa开发者_StackOverflow中文版y? It seems to me that this solution is a bit clumsy. (considering in each catch block you create el object and call its method, repeatedly.)

Also, in terms of storing error log files, where it the best / most reasonable location to save them? Currently, I just hard-coded the directory, C:\ErrorLogs\, as I am still testing a few things. But I do want to get it right before I forget.

So any ideas or suggestions?

Thanks.


Look at ELMAH This is very efficient in handling and catching errors in the application.

The errors get logged in the database.


Usually I'm using the Singleton pattern to have one application wide Logger.

public class Logger
{
    protected static Logger _logger;

    protected Logger()
    {
        // init
    }

    public void Log(string message)
    {
        // log
    }

    public static Logger GetLogger()
    {
        return _logger ?? _logger = new Logger();
    }
}

As a place to store data I would use the application data or user data directory, only there you can be sure to have write access.

Edit: That's how you would use the Logger from any place in your code:

Logger.GetLogger().Log("test");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号