本文介绍了Log4Net无法使用UnityContainer登录.NET WebApi项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常基本的C#.NET WebApi项目,使用Unity.AspNet.WebApi和Unity.Mvc进行依赖项注入,并使用Unity.log4net进行日志记录.

I have a very basic C# .NET WebApi project using Unity.AspNet.WebApi and Unity.Mvc for dependency injection and Unity.log4net for logging.

注入到我的控制器中似乎工作正常.问题是记录器从不记录任何内容.永远不会创建预期的.log文件.当我在调试时检查记录器对象时,它已禁用所有级别(IsDebugEnable = false,IsErrorEnabled = false等)

The injection into my controllers seems to be working correctly. The problem is that the logger never logs anything. The expected .log file is never created. When I inspect the logger object while debugging it has all the levels disabled (IsDebugEnable = false, IsErrorEnabled = false, etc.)

它正在运行,好像已经忽略了我的log4net.config文件.在我项目的根目录中,我有一个log4net.config文件,该文件定义了一个控制台和一个文件附加器.

It is running as if has ignored my log4net.config file. In the root of my project I have a log4net.config file that defines a console and a file appender.

<log4net>
  <root>
    <level value="ALL" />
    <appender-ref ref="console" />
    <appender-ref ref="file" />
  </root>
  <appender name="console" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %level %logger - %message%newline" />
    </layout>
  </appender>
  <appender name="file" type="log4net.Appender.RollingFileAppender">
    <file value="DemoWebApiUnityLog4Net.log" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="5" />
    <maximumFileSize value="10MB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
    </layout>
  </appender>
</log4net>

我已将此行添加到AssemblyInfo.cs

I have added this line to AssemblyInfo.cs

[assembly: log4net.Config.XmlConfigurator(ConfigFile = @"log4net.config", Watch = true)]

log4net通过以下行在UnityConfig.cs中注册到Unity容器中:

The log4net was registered in to the Unity container in UnityConfig.cs with this line:

container.AddNewExtension<Log4NetExtension>();

完整的演示项目可以在这里找到: https://github.com/CarmonColvin/DemoWebApiUnityLog4Net

The full demo project can be found here: https://github.com/CarmonColvin/DemoWebApiUnityLog4Net

我尝试过的所有操作均未成功完成日志.感谢您的帮助.

Nothing I have tried has resulted in a successful log. Any help is appreciated.

推荐答案

根据log4net 常见问题解答:

According to the log4net FAQ:

因此,在我看来,应该在应用程序启动时在Global.asax中调用LogManager.GetLogger()来加载配置.像这样:

So it sounds to me like you should be calling LogManager.GetLogger() in Global.asax when the application starts in order to load your configuration. Something like:

using log4net;

protected void Application_Start(object sender, EventArgs e)
{
    var logger = LogManager.GetLogger(typeof(Global));
    logger.Info("Application started.");
}

这篇关于Log4Net无法使用UnityContainer登录.NET WebApi项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 13:33