What would a Log4Net Wrapper class look like?

后端 未结 9 1049
失恋的感觉
失恋的感觉 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 05:58

    There are frameworks like the Prism Library for WPF that promote the usage of a facade for the logging framework of your choice.

    This is an example that uses log4net:

    using System;
    using log4net;
    using log4net.Core;
    using Prism.Logging;
    
    public class Log4NetLoggerFacade : ILoggerFacade
    {
        private static readonly ILog Log4NetLog = LogManager.GetLogger(typeof (Log4NetLoggerFacade));
    
        public void Log(string message, Category category, Priority priority)
        {
            switch (category)
            {
                case Category.Debug:
                    Log4NetLog.Logger.Log(typeof(Log4NetLoggerFacade), Level.Debug, message, null);
                    break;
                case Category.Exception:
                    Log4NetLog.Logger.Log(typeof(Log4NetLoggerFacade), Level.Error, message, null);
                    break;
                case Category.Info:
                    Log4NetLog.Logger.Log(typeof(Log4NetLoggerFacade), Level.Info, message, null);
                    break;
                case Category.Warn:
                    Log4NetLog.Logger.Log(typeof(Log4NetLoggerFacade), Level.Warn, message, null);
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(category), category, null);
            }
        }
    }
    

    Note that by specifying the callerStackBoundaryDeclaringType you can still get the class name of the caller issuing the logging request. All you need to do is to include %C %M in your conversion pattern:

    
        
    
    

    However, as the documentation warns, generating the caller class information is slow, therefore it must be used wisely.

提交回复
热议问题