What would a Log4Net Wrapper class look like?

后端 未结 9 996
失恋的感觉
失恋的感觉 2020-12-02 05:19

I have been looking for a logging framework for .net (c#) and decided to give log4net a go after reading up on a few question/answer threads here on stackoverflow. I see peo

9条回答
  •  醉梦人生
    2020-12-02 06:03

    Alconja, I like your idea of using the stacktrace to jump back to the calling method. I was thinking of further encapsulating the calls, to not just retrieve the logger object, but to perform actually perform the logging. What I want is a static class that handles the logging, by abstracting from the specific implementation used. I.e.

    LoggingService.LogError("my error message");
    

    That way I only need to change the internals of the static class, if I later decide to user another logging system.

    So I used your idea to get the calling object using the stack trace :

    public static class LoggingService
    {
        private static ILog GetLogger()
        {    
            var stack = new StackTrace();    
            var frame = stack.GetFrame(2);    
            return log4net.LogManager.GetLogger(frame.GetMethod().DeclaringType);
        }
    
        public static void LogError(string message)
        {
            ILog logger = GetLogger();
            if (logger.IsErrorEnabled)
                logger.Error(message);
        }
        ...
    }
    

    Does anybody see a problem with this approach?

提交回复
热议问题