Search code examples
.netdependency-injectionwindows-servicesautofaclog4net

Implement log4net in a windows service using dependency injection


I want to write error if occur in log file in a windows service which runs in every 10 minutes. I am using .net framework 4.6 and using Dependency Injection with autofac. I want to use Microsoft.Extensions.Logging dll.


Solution

  • I did this in a Windows Service, with ASP.Net 4.8, and Autofac for DI. I also didn't have to add any assembly info in AssemblyInfo.cs, because I put the config info in the app.config, instead of a separate config file.

    app.config put this at the top of your app.config file just after <configuration>

    <configuration>
        <configSections>
            <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
        </configSections>
    

    log4net configuration put this at the bottom of your app.config file, just inside </configuration>. It will print to your visual studio output window and to a file called myservice.log

    <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="myservice.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>
    </configuration>
    

    Program.cs

    static void Main()
    {
                ContainerBuilder cb = new ContainerBuilder();
                cb.RegisterType<MyService>().AsSelf().InstancePerLifetimeScope();
                log4net.Config.XmlConfigurator.Configure();
                ServiceBase.Run(container.Resolve<MyService>());
    }
    

    MyService.cs

    private readonly ILog _logger;
    public MyService(ILog logger)
    {
        InitializeComponent();
        _logger = logger;
        _logger.Info("Hello World!");
    }