【发布时间】:2015-01-19 15:51:23
【问题描述】:
我想知道如何使用 log4net(在我的示例中)以 %logger 模式打印正确的类名。
在我的应用程序中,我正在使用实现日志接口的日志类(遵循 SOLID)。其他类使用日志接口抽象来执行实际的日志记录。我想切换到 Log4Net,但我正在考虑保留日志记录抽象。自定义日志记录类方法将对象作为参数并根据它们的状态创建日志。
因此,在下面的示例中,%logger 模式将记录“MyLogger”,这是预期的,但我想记录调用类名称(在本例中为 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();
}
}
}
【问题讨论】: