I am converting from Prism 2.1 to Prism 4, and I need to write an ILoggerFacade class for Log4Net. My old code from Prism 2.1 no longer works. Does anyone have sample code for an ILoggerFacade class they'd be willing to share? Thanks for your help.
I figured it out. Very similar to Prism 2. First, create a custom logger class that implements ILoggerFacade. Here's my class:
using log4net;
using Microsoft.Practices.Prism.Logging;
namespace FsNoteMaster3
{
class Log4NetLogger : ILoggerFacade
{
#region Fields
// Member variables
private readonly ILog m_Logger = LogManager.GetLogger(typeof(Log4NetLogger));
#endregion
#region ILoggerFacade Members
/// <summary>
/// Writes a log message.
/// </summary>
/// <param name="message">The message to write.</param>
/// <param name="category">The message category.</param>
/// <param name="priority">Not used by Log4Net; pass Priority.None.</param>
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;
}
}
#endregion
}
}
Then, in the Prism 4 Bootstrapper class, add an override to the CreateLogger()
method that returns a new instance of the custom logger class:
protected override Microsoft.Practices.Prism.Logging.ILoggerFacade CreateLogger()
{
return new Log4NetLogger();
}
Note that in the custom logger class, ILog
is a Log4Net interface, and LogManager
is a Log4Net object.
Writing to the custom logger from your own code (Prism takes care of its own log entries)is a little different than in Prism 2.1. You can resolve the logger directly from the IoC container, or you can use the ServiceLocator. The ServiceLocator
has the advantage of being container-agnostic, which means the underlying container doesn't really matter. Here is an example of resolving a logger using the ServiceLocator:
var logger = (Log4NetLogger)ServiceLocator.Current.GetInstance(typeof(ILoggerFacade));
logger.Log("App.OnStartup() completed", Category.Info ,Priority.None);
The ServiceLocator
requires that the host project have a reference to Microsoft.Practices.ServiceLocation.dll and a matching using
statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With