- 4 minutes to read

How to implement Log4Net in a new .NET Application

This page describes the steps to add the Nodinite Log4Net Appender to your Visual Studio Project.

Note: We recommend that you try the SeriLog appender instead of using the old-school Log4Net appender.

Step 1. Add package reference

Start by adding the Nodinite Log4Net Nuget Package to your Visual Studio project.
Add NuGet Package Reference

Package on NuGet.org

Step 2. Create handle

Then, add a variable to acquire a handle to the Log4Net instance:

var log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); 

Step 3. Include namespace

Resolve the issue with the missing namespace by adding a using declaration at the top of the Class:

using log4net;

Step 4. Add the Log4Net configuration file

Add the log4net.config file, make sure to set Copy to Output Directory to Copy Always.

Step 5. Manage Log4Net configuration

Add the following XML configuration to the log4net.config file (Change values to your liking):

The fields map 1:1 with the Nodinite JSON Log Event. LogText (Exception object) and LogStatus are implicitly provided in your code. NOTE: The message param is the Body in Nodinite. In the example below these properties are provided in case you need to override this behaviour.

Make sure to set the LogApiServiceURI with a valid Address to the Nodinite Log API.

    <log4net>
	<appender name="Log4NetAppender" type="Nodinite.LogAgent.Log4NetAppender.NodiniteLog4NetAppender,Nodinite.LogAgent.Log4NetAppender">
		<!-- Custom Parameters -->
		<OriginalMessageType value="Nodinite.LogAgent.Log4NetAppender/2.0#DefaultMessageType" />
		<MessageTypeExtractFromBody value="false" />
		<LogAgentID value="101"/>
		<EventNumber value="0"/>
		<EndPointName value="Log4Net Unit Test"/>
		<EndPointUri value="VS.local.log4net.test"/>
		<!--<LogText value =""/>--> <!-- Should not be part of the configuration file -->
		<!--<LogStatusId value ="255"/>--> <!-- Should not be part of the configuration file -->
		<ProcessingUser value="Administrator"/>
		<ModuleType value="unit test"/>
		<ProcessName value="unit test"/>
		<ProcessingMachineName value="DEV"/>
		<ProcessingModuleType value="unit test"/>
		<ProcessingModuleName value="VS"/>
		<LogApiServiceURI value="http://localhost/Nodinite/Dev/logapi"/>
		<ApplicationInterchangeId value="{99106FF5-C7BB-4244-9EB7-F99040190F32}"/>
		<LocalInterchangeId value="{E4CDDF18-9925-4A79-8E9F-71BC0D4C5172}"/>
		<ServiceInstanceActivityId value="{E4CDDF18-9925-4A79-8E9F-71BC0D4C5173}"/>
	</appender>
	<root>
		<level value="DEBUG"/>
		<appender-ref ref="Log4NetAppender"/>
	</root>
</log4net>

Step 6. Add Watcher

Add the line: [assembly: log4net.Config.XmlConfigurator(Watch = true)] to the Properties.cs file to make sure Log4Net reflects changes in the configuration file during run-time.

Step 7. Initialize Log4Net configuration

The code is different depending on the type of .NET run-time:

.NET Framework

Example using a .NET Framework (>4.6.2) solution.

var fileInfo = new System.IO.FileInfo("log4net.config");
XmlConfigurator.Configure(fileInfo);

.NET

Worker service example.

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddLogging(loggingBuilder =>
        {
            loggingBuilder.AddLog4Net();
        });
        services.AddHostedService<Worker>();
    })
    .Build();

Step 8. Perform Logging

Perform the logging by adding code depending on the different Log levels, view examples below:

Info example

// Message is payload (Body)
log.Info("<Orders><Order><Id>123</Id></Order></Orders>");

Error example

// Message is payload (Body), Exception is LogText
log.Error("<Orders><Order><Id>123</Id></Order></Orders>", new Exception("Guru Meditation"));

Next step

Log API