【发布时间】:2010-11-29 17:26:53
【问题描述】:
我正在编写一个日志记录类,我希望能够获得调用Helper.Log(string message) 的类的名称。
这可以使用反射和 c# 吗?
【问题讨论】:
标签: c# reflection
我正在编写一个日志记录类,我希望能够获得调用Helper.Log(string message) 的类的名称。
这可以使用反射和 c# 吗?
【问题讨论】:
标签: c# reflection
是的,这很容易。
Helper.Log("[" + this.GetType().Name + "]: " + message);
【讨论】:
请注意,如果您的 logger 类确实是日志框架(如 log4net 或 NLog)的包装器,则可以将日志框架配置为为您获取调用类/方法。要使其正常工作,您必须正确包装日志框架。对于 NLog 和 log4net,正确包装(以保留调用站点信息)通常涉及使用“日志”方法(而不是错误、警告、信息等变体)并将“记录器类型”作为第一个参数传递。 “记录器类型”是包装日志框架记录器的记录器的类型。
这是包装 NLog (taken from here) 的一种方法:
class MyLogger
{
private Logger _logger;
public MyLogger(string name)
{
_logger = LogManager.GetLogger(name);
}
public void WriteMessage(string message)
{
///
/// create log event from the passed message
///
LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, _logger.Name, message);
// Call the Log() method. It is important to pass typeof(MyLogger) as the
// first parameter. If you don't, ${callsite} and other callstack-related
// layout renderers will not work properly.
//
_logger.Log(typeof(MyLogger), logEvent);
}
}
以下是您可以使用 log4net 的方法:
class MyLogger
{
private ILog _logger;
public MyLogger(string name)
{
_logger = LogManager.GetLogger(name);
}
public void WriteMessage(string message)
{
// Call the Log() method. It is important to pass typeof(MyLogger) as the
// first parameter. If you don't, ${callsite} and other callstack-related
// formatters will not work properly.
//
_logger.Log(typeof(MyLogger), LogLevel.Info, message);
}
}
【讨论】: