Ford's Garage

Small garage of one Ford in the big internet


log4net Quick Start


Install log4net

dotnet add package log4net --version 2.0.15

Create config file log4net.config


<log4net>

    <root>

        <level value="ALL" />

        <appender-ref ref="console" />

        <!-- <appender-ref ref="file" /> -->

    </root>



    <!--Console appender-->

    <appender name="console" type="log4net.Appender.ManagedColoredConsoleAppender">

        <mapping>

            <level value="DEBUG" />

            <forecolor value="Blue" />

        </mapping>

        <mapping>

            <level value="INFO" />

            <forecolor value="White" />

        </mapping>

        <mapping>

            <level value="WARN" />

            <forecolor value="Yellow" />

        </mapping>

        <mapping>

            <level value="ERROR" />

            <forecolor value="Red" />

        </mapping>

        <mapping>

            <level value="FATAL" />

            <backcolor value="Red" />

            <forecolor value="White" />

        </mapping>

        <layout type="log4net.Layout.PatternLayout">

            <conversionpattern value="%date [%thread] %-5level - %message%newline" />

        </layout>

    </appender>



    <appender name="file" type="log4net.Appender.RollingFileAppender">

        <file value="error.log" />

        <appendToFile value="true" />

        <rollingStyle value="Size" />

        <maxSizeRollBackups value="1" />

        <maximumFileSize value="1MB" />

        <staticLogFileName value="true" />

        <layout type="log4net.Layout.PatternLayout">

            <conversionPattern value="%date [%thread] %level %logger - %message%newline" />

        </layout>

    </appender>

</log4net>

Modify .csproj-file to include config


<ItemGroup>

  <None Update="log4net.config">

    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>

  </None>

</ItemGroup>

Modify your code to enable logging


using System.Reflection;
using log4net;
using log4net.Config;

namespace ConsoleApp1
{
    internal static class Program
    {
        private static ILog _log = null!;

        private static void Main(string[] args)
        {
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
            _log = LogManager.GetLogger(typeof(Program));
            
            _log.Debug("Info message");
            _log.Info("Info message");
            _log.Warn("Info message");
            _log.Error("Info message");
            _log.Fatal("Info message");
        }
    }
}