c# – 如何在log4net消息中添加类别前缀?
发布时间:2020-12-15 08:41:52  所属栏目:百科  来源:网络整理 
            导读:我想为现有日志消息上的所有消息添加类别前缀.但是,将此前缀逐个添加到所有现有日志记录消息中非常繁琐.有没有办法可以在类级别添加一个属性,那么这个类中的所有消息都会记录到某个类别? 而不是现在的方式如下, Log.Info("[Ref] Level 1 Starts ..."); 我真
                
                
                
            | 我想为现有日志消息上的所有消息添加类别前缀.但是,将此前缀逐个添加到所有现有日志记录消息中非常繁琐.有没有办法可以在类级别添加一个属性,那么这个类中的所有消息都会记录到某个类别? 
  
  而不是现在的方式如下, Log.Info("[Ref] Level 1 Starts ...");我真的想要这样或类似的方式来定义log4net.ILog. [LoggingCategory("Ref")]
public class MyClass 
{
   public void MyMethod()
   {
        Log.Info("Level 1 Starts ...");
   }
}解决方法
 有趣的问题,粗略的尝试…… 
  
  Log4NetLogger – 日志适配器 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 – 适用于类 [AttributeUsage(AttributeTargets.Class)]
public class LoggingCategoryAttribute : Attribute
{
    private readonly string _category;
    public LoggingCategoryAttribute(string category)
    {
        _category = category;
    }
    public string Category { get { return _category; } }
}LogTester – 一个测试实现 [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");
    }
}(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! | 
