gpt4 book ai didi

c# - 如何向 log4net 消息添加类别前缀?

转载 作者:太空狗 更新时间:2023-10-29 20:01:58 26 4
gpt4 key购买 nike

我喜欢为现有日志消息上的所有消息添加类别前缀。然而,将这个前缀一一添加到所有现有的日志消息中是很乏味的。有没有一种方法可以在类级别中添加一个属性,然后将针对某个类别记录此类中的所有消息?

而不是现在的方式如下,

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

关于c# - 如何向 log4net 消息添加类别前缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4454755/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com