Log4Net in .NetCore simple example

This is a simple example of using Log4net in .net core console app.

Create a new console app

dotnet new console
Add log4net
dotnet add package log4net
Replace Progam.cs with this

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

var log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
var logrepo = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logrepo, new FileInfo("log4net.config"));

log.Info("this is INFO");
Create a new file log4net.config and add this

<log4net>
    <root>
        <appender-ref ref="ConsoleAppender"/>
    </root>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%d [%t] %-5p %logger - %m%n" />
        </layout>
    </appender>
</log4net>

Now run the program and you should see the output
C:\Temp\log4net\console>dotnet run
2022-03-25 13:22:55,601 [1] INFO  Program - this is INFO
Gist

Comments

Popular posts from this blog

Adding CKEditor 4 to Angular

Using @CurrentIteration with TFS API