What would a Log4Net Wrapper class look like?

后端 未结 9 807
失恋的感觉
失恋的感觉 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:00

    My understanding is that a wrapper class for log4net would be a static class which takes care of initializing the logging object from app.config/web.config or by code (e.g. integration with NUnit).

    0 讨论(0)
  • 2020-12-02 06:02

    What benefits are you planning on getting out of writing a wrapper for log4net. I'd recommend getting comfortable with the log4net classes first before writing a wrapper around them. cfeduke is right in his answer on how to write said wrapper, but unless you need to add actual functionality to his example a wrapper would only succeed in slowing the logging process down and adding complexity for future maintainers. This especially true when refactoring tools available in .Net make such changes super easy.

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

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