C#-Log4net附加程序始终为空

我在我的webapi项目中使用log4net(使用autofac和owin).我将此添加到我的控制器

LogManager.GetLogger(typeof(NotificationController));

但是我已经看到没有加载附加程序.在我的配置中我有这个

 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
...    
<log4net>
        <root>
          <level value="ALL" />
          <appender-ref ref="aiAppender" />
          <appender-ref ref="TraceAppender" />
          <appender-ref ref="FileAppender" />
        </root>
        <appender name="aiAppender" type="Microsoft.ApplicationInsights.Log4NetAppender.ApplicationInsightsAppender, Microsoft.ApplicationInsights.Log4NetAppender">
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%message%newline" />
          </layout>
        </appender>
        <appender name="TraceAppender" type="log4net.Appender.TraceAppender">
          <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%d [%t] %-5p %m%n" />              
          </layout>
        </appender>
        <appender name="FileAppender" type="log4net.Appender.FileAppender">
          <file value="log\server.log" />
          <appendToFile value="true" />
          <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%d [%t] %-5p %m%n" />
          </layout>
        </appender>
      </log4net>

我没有构建错误,如果我调用此代码,我的代码将运行无错误

logger.Fatal("Error");

但是我没有日志.

更新

将此添加到启动类,但不会更改

public class Startup
{
    private static readonly ILog logger = LogManager.GetLogger(typeof(Startup));

    public void Configuration(IAppBuilder app)
    { 
        HttpConfiguration config = new HttpConfiguration();

        logger.Info("Start application");

解决方法:

必须明确告知Log4Net,您希望它从App.config中读取XML配置.

查看:log4net only works when XmlConfigurator.Configure() is called

在应用程序启动代码中调用静态方法XmlConfigurator.Configure(),或将以下内容添加到解决方案中所有项目的AssemblyInfo.cs中:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

您可能还会发现,启动后必须立即调用LogManager.GetLogger()-即使记录程序实例未用于任何操作,这似乎也有所不同.

上一篇:c#-Windows和Mono之间的日期时间差异以及log4net远程附加程序


下一篇:C#-log4net:无法加载类型’log4net.Appender.AdoNetAppender’