作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我喜欢为现有日志消息上的所有消息添加类别前缀。然而,将这个前缀一一添加到所有现有的日志消息中是很乏味的。有没有一种方法可以在类级别中添加一个属性,然后将针对某个类别记录此类中的所有消息?
而不是现在的方式如下,
Log.Info("[Ref] Level 1 Starts ...");
[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/
我是一名优秀的程序员,十分优秀!