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