问题
I'm trying to implement logging functionality into my new WPF 4.5 CompositeWPF (Prism) project.
This requires me to implement ILoggerFacade in my code. The interface only implements 1 method: Log(string message, Category category, Priority priority)
.
The ILoggerFacade
interface:
public interface ILoggerFacade
{
void Log(string message, Category category, Priority priority);
}
My implementation :
public class Log4NetLogger : ILoggerFacade
{
private static readonly ILog m_Logger = LogManager.GetLogger(typeof(ILoggerFacade));
public void Log(string message, Category category, Priority priority)
{
switch (category)
{
case Category.Debug:
m_Logger.Debug(message);
break;
case Category.Warn:
m_Logger.Warn(message);
break;
case Category.Exception:
m_Logger.Error(message);
break;
case Category.Info:
m_Logger.Info(message);
break;
}
}
}
I believe that with newly introduced [CallerMemberName]
attribute I should be able to get the caller method name passed to the logger if only I knew how to do something like this:
public class Log4NetLogger : ILoggerFacade
{
public void Log(string message, Category category, Priority priority, [CallerMemberName] string callerMethod = "")
{
...
So my question, how do I override the Log
method enforced by third party (Prism) interface to contain 1 additional, optional parameter? Or how do I pass the caller method name using this attribute so I can log it?
I have seen other similar questions but [CallerMemberName] attribute is a new feature in .NET 4.5 so I'm hoping for a better solution than the ones presented.
回答1:
Unfortunately the only way you would be able to make this work is to modify the Prism source and rebuild the binaries. e.g. add the callerMethod parameter to the Log method of ILoggerFacade.
public interface ILoggerFacade
{
void Log(string message, Category category,
Priority priority, [CallerMemberName] string callerMethod = "");
}
And if there are any classes already implementing ILoggerFacade you will need to modify them also.
回答2:
You can extend ILoggerFacade interface with some extra methods, like so:
public static class LoggerExtensions
{
public static void LogError(this ILoggerFacade logger, string message, [CallerMemberName] string caller = "")
{
logger.Log(message + ' ' + caller, Category.Exception, Priority.High);
}
}
Then you just use your extended methods instead of Log():
logger.LogError("message");
来源:https://stackoverflow.com/questions/15258263/how-to-change-iloggerfacade-implementation-to-trace-caller-method-using-callerme