我正在使用Ninject 3.0.1.10 进行依赖注入,并希望将Ninject.Extensions.Logging 3.0.1.0 用于log4net 1.2.11 日志记录。但是,当我使用扩展而不是直接使用 log4net 时,我的日志文件中会得到不同的输出。我希望输出包含执行日志记录的类/方法的名称,如下在我的 app.config 中:
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="MyConsoleAppender" />
</root>
<appender name="MyConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %C{1}.%M():%L - %m%n" />
</layout>
</appender>
</log4net>
我制作了一个示例项目来演示我看到的问题,如下所示:
public class LoggingWithLog4Net
{
private readonly ILog log;
public LoggingWithLog4Net(ILog log)
{
this.log = log;
}
public void LogMessage(string message)
{
log.Debug(message);
}
}
public class LoggingWithNinject
{
private readonly ILogger log;
public LoggingWithNinject(ILogger log)
{
this.log = log;
}
public void LogMessage(string message)
{
log.Debug(message);
}
}
public class Program
{
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
NinjectSettings settings = new NinjectSettings()
{
LoadExtensions = false
};
using (IKernel kernel = new StandardKernel(settings, new Log4NetModule()))
{
kernel.Bind<ILog>()
.ToConstant(LogManager.GetLogger("*"));
LoggingWithLog4Net l4n = kernel.Get<LoggingWithLog4Net>();
LoggingWithNinject ninject = kernel.Get<LoggingWithNinject>();
l4n.LogMessage("log4net message");
ninject.LogMessage("ninject message");
}
}
}
这会产生以下输出(注意 Ninject 版本中的类/方法名称不正确):
2012-06-21 08:25:19,000 DEBUG LoggingWithLog4Net.LogMessage():21 - log4net message
2012-06-21 08:25:19,015 DEBUG Log4NetLogger.Debug():98 - ninject message
我希望第二行LoggingWithNinject.LogMessage():21
作为源类/方法,但 NinjectLog4NetLogger
被用作源。如何正确识别来源?