c# – 如何在log4net消息中添加类别前缀?

我想为现有日志消息上的所有消息添加类别前缀.但是,将此前缀逐个添加到所有现有日志记录消息中非常繁琐.有没有办法可以在类级别添加一个属性,那么这个类中的所有消息都会记录到某个类别?

而不是现在的方式如下,

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");
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


c语言数组越界会怎么样
c语言指针怎么等于数组
c语言数组怎么存入文字
c语言中怎么显示数组
c语言数组元素怎么选
c语言数组怎么累加
c语言数组符号怎么输入
c语言怎么用长数组
c语言数组函数怎么输入
c语言数组怎么去掉差异
c语言怎么求解数组
c语言数组怎么用变量
c语言怎么申明数组
c语言怎么控制数组
c语言怎么计算数组长度
c语言数组怎么插星号
c语言数组怎么加长度
c语言中怎么输出数组
c语言怎么记住数组边界
c语言数组怎么输入符号