I would like to know how to print the right class name in the %logger pattern using log4net (in my example).
In my app I am using a logging class implementing a logging interface (following SOLID). Other classes use the logging interface abstraction to perform the actual logging. I want to switch to Log4Net, but I was thinking of keeping the logging abstraction. The custom logging class methods take objects as arguments and create logs basing on their states.
So in the below example the %logger pattern will log "MyLogger", which is expected, but I would like to log the calling class name (in this case ObjectManipulator).
using System.Reflection;
using log4net;
namespace LoggingTestur
{
class Program
{
class AnObject
{
public string State { get; set; }
}
interface IMyLogger
{
void LogObjectStateChenge(AnObject anObject);
}
class MyLogger : IMyLogger
{
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public void LogObjectStateChenge(AnObject anObject)
{
Log.InfoFormat("AnObject's state is: {0}", anObject.State);
}
}
class ObjectManipulator
{
private readonly IMyLogger _logger;
public ObjectManipulator(IMyLogger logger)
{
_logger = logger;
}
public void Manipulate()
{
var anObject = new AnObject { State = "New" };
_logger.LogObjectStateChenge(anObject);
}
}
static void Main(string[] args)
{
var logger = new MyLogger();
var manipulator = new ObjectManipulator(logger);
manipulator.Manipulate();
}
}
}