How to add category prefix to log4net message?

前端 未结 2 2121
醉酒成梦
醉酒成梦 2021-02-04 16:18

I like to add category prefix to all the messages on the existing logging messages. However it is tedious to add this prefix to all the existing logging messages one by one. Is

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 17:05

    Interesting problem, rough attempt...

    Log4NetLogger - logging adapter

    public class Log4NetLogger
    {
        private readonly ILog _logger;
        private readonly string _category;
    
        public Log4NetLogger(Type type)
        {
            _logger = LogManager.GetLogger(type);
            _category = GetCategory();
        }
    
        private string GetCategory()
        {
            var attributes = new StackFrame(2).GetMethod().DeclaringType.GetCustomAttributes(typeof(LoggingCategoryAttribute), false);
            if (attributes.Length == 1)
            {
                var attr = (LoggingCategoryAttribute)attributes[0];
                return attr.Category;
            }
            return string.Empty;
        }
    
        public void Debug(string message)
        {
            if(_logger.IsDebugEnabled) _logger.Debug(string.Format("[{0}] {1}", _category, message));
        }
    }
    

    LoggingCategoryAttribute - applicable to classes

    [AttributeUsage(AttributeTargets.Class)]
    public class LoggingCategoryAttribute : Attribute
    {
        private readonly string _category;
    
        public LoggingCategoryAttribute(string category)
        {
            _category = category;
        }
    
        public string Category { get { return _category; } }
    }
    

    LogTester - a test implementation

    [LoggingCategory("LT")]
    public class LogTester
    {
        private static readonly Log4NetLogger Logger = new Log4NetLogger(typeof(LogTester));
    
        public void Test()
        {
            Logger.Debug("This log message should have a prepended category");
        }
    }
    

提交回复
热议问题