I'm writing a logging class and I would like to be able to get the name of the class that has the call to Helper.Log(string message)
.
Is this possible using reflection and c#?
I'm writing a logging class and I would like to be able to get the name of the class that has the call to Helper.Log(string message)
.
Is this possible using reflection and c#?
Yes, it is quite easy.
Helper.Log("[" + this.GetType().Name + "]: " + message);
Note that if your logger class is really a wrapper around a logging framework (like log4net or NLog), the logging framework can be configured to get the calling class/method for you. For this to work correctly, you have to wrap the logging framework correctly. For NLog and log4net, correctly wrapping (to preserve call site information) generally involves using the "Log" method (rather than the Error, Warn, Info, etc variants) and passing the "logger type" as the first parameter. The "logger type" is the type of your logger that wraps the logging framework's logger.
Here is one way to wrap 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);
}
}
And here is how you could do it with 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);
}
}