---
title: Implement Log4Net Appender in a New .NET Application
description: Learn how to implement the Nodinite Log4Net Appender in a new .NET application. This guide covers step-by-step integration, configuration, and advanced logging features for seamless monitoring and troubleshooting.
---

# How to implement Log4Net in a new .NET Application

Easily integrate the :Nodinite: [Log4Net Appender][] into your .NET applications for advanced, centralized logging and monitoring. This guide walks you through every step, from NuGet installation to advanced configuration, so you can:

* ✅ Achieve seamless log integration with :Nodinite:  
* ✅ Leverage advanced configuration and override options  
* ✅ Enable robust monitoring and troubleshooting  
* ✅ Support both .NET Framework and modern .NET projects  

:fa-arrow-down-to-square: [Package on **NuGet.org**](https://www.nuget.org/packages/Nodinite.LogAgent.Log4NetAppender)<sup>:fa-arrow-up-right-from-square:</sup>

>[!INFO]
>This page describes the steps about how to add the :Nodinite: [Log4Net Appender][] to your Visual Studio Project and Log events using the [Log4Net][Log4NetApache] framework to :Nodinite:.

>[!TIP]
>You should use the [Serilog][] if you are using .NET.

## :fa-forward-step: Step 1. Add package reference

Start by adding the :Nodinite: Log4Net Nuget Package to your Visual Studio project.  
![Add NuGet Package Reference][1]
*Add the Nodinite Log4Net Appender NuGet package to your Visual Studio project.*

## :fa-forward-step: Step 2. Create handle

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

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

*.NET Framework.*

## :fa-forward-step: Step 3. Include namespace

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

```csharp
using log4net;
```

*.NET Framework.*

## :fa-forward-step: Step 4. Add the Log4Net configuration file

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

>[!TIP]
>You can [override](#override-configuration-values) the configuration values in code!

## :fa-forward-step: Step 5. Manage Log4Net configuration

Add the following default XML configuration to the `log4net.config` file (Change values to your liking or even better, [overide](#override-configuration-values) the run-time values in code).  

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** (Payload) in :Nodinite:.

```xml
    <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"/>
        <EventDirection value="66">
        <EndPointDirection value="-2">
        <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="https://localhost:40002/LogAPI/"/>
        <ApplicationInterchangeId value="RUN-123">
        <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>
```

>[!IMPORTANT]
>Ensure the **LogApiServiceURI** has a valid address (URI) to the :Nodinite: [Log API][] (the host and port come from your environment's settings in the :Nodinite: Portal ([Servers step][])) OR has a folder that exist on disk. Make sure the path ends with a trailing backslash `\`.

### LogApiServiceURI

||LogApiServiceURI|Comment|  
|---|---|---|  
|:fa-globe: [Log API][]|`https://localhost:40002/LogAPI/`|**NOTE:** The call is **synchronous**, hence, if service is unavailable, you will lose the log event|  
|:fa-folder: Folder :new6.0.8:|`c:\temp\`|Ensure the target folder is highly available. Use the :Nodinite: [Pickup Log Events Service Logging Agent][Pickup Service] to consume the files, and use the :Nodinite: [File Monitoring Agent][] to ensure the files do not stockpile|  

### What's New in Version 6.0.8

:new6.0.8:

* `LogText` can be set unless you are logging an Exception.  
  >[!NOTE]
  >Internally, the `LogText` is set to null on each Log. You must set it again for each event to be logged.

* `ApplicationInterchangeId` can be a string.  
* [EndPointDirection][Endpoint Directions] can be set, the default is "None (-2)".
* [EventDirection][EventDirections] can be set, default is "Process Outgoing (66)".
* All config values except `MessageTypeExtractFromBody` can be [overriden in code](#override-configuration-values).  
* [LogApiServiceURI](#logapiserviceuri) can either be a folder, or an address to the :Nodinite: [Log API][].  
* `SequenceNo` can be set programmatically (should not be set in config file).  

### What's New in Version 6.0.0.9

:new6.0.0.9:

You can set the [Log4Net Appender][] to legacy mode, by default, this option is turned off. We built the Logger to Log Business Transactions. If you set this property to `true`, then `Hello World` is in the Log Text field if your code is:  `_logger.LogInformation("Hello World");`.

This is a new property to set in the config file

```xml
<LogMessageObjectAsLogText value="true"/>
```

*Set the `LogMessageObjectAsLogText` to `true` to enable legacy mode.*

>[!NOTE]
>This settings also affects logging errors!

## :fa-forward-step: 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.

## :fa-forward-step: Step 7. Initialize Log4Net configuration

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

* [.NET Framework](#net-framework)
* [.NET](#net)

### .NET Framework

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

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

### .NET

Worker service example.

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

## :fa-forward-step: Step 8. Perform Logging

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

### Log using the .NET Framework

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

*Here's an example of a simple .NET Framework-based Logging example.*

### Log using .NET

```csharp
public class Worker
 {
     private readonly ILogger<Worker> _logger;

     public Worker(ILogger<Worker> logger)
     {
         _logger = logger;
     }
     
     public void DoLogging()
     {
        _logger.LogInformation("<Orders><Order><Id>{OrderId}</Id></Order></Orders>", 123);
        _logger.LogError(ex, "<Orders><Order><Id>{OrderId}</Id></Order></Orders>", 123);
     }
}
```

*Here's an example of a simple .NET-based Logging example.*

### Error example (.NET)

### Override Configuration Values

:new6.0.8:
All configuration values can be overriden using the name as in the example below:  

```csharp
log4net.GlobalContext.Properties["ApplicationInterchangeId"] = "RUN-456";
log4net.GlobalContext.Properties["SequenceNo"] = 1;
log.Info("<Orders><Order><Id>123</Id></Order></Orders>");
```

*.NET Framework example.*

```csharp
log4net.GlobalContext.Properties["ApplicationInterchangeId"] = "RUN-456";
log4net.GlobalContext.Properties["SequenceNo"] = 2;
log4net.GlobalContext.Properties["LogText"] = "Finished Processing";
_logger.LogInformation(""); //NOTE: LogText is set on previous row
```

*.NET Framework example.*

### Add any Context

:new6.0.8:
You can add arbitrary Key/Values as to the `Context`. These will appear as **Context Properties** in the :Nodinite: [Log Event][]. Then, you can create [Search Fields][] and
use the [Message Context Key][] plugin to have :Nodinite: extract the values. Use this in :Nodinite: [Log Views][] and allow your business users to gain access, and search for data.

```csharp
log4net.GlobalContext.Properties["Context"] = new Dictionary<string, string>
 {
     { "Key1", "Value1" },
     { "Key2", "Value2" }
 };
```

>[!INFO]
>The code above applies to .NET and .NET Framework.

### Example overriding all config values

```csharp
log4net.GlobalContext.Properties["LogText"] = "SAMPLE:LogText"; // NOTE: This value is reset after EACH log event
log4net.GlobalContext.Properties["LogApiServiceURI"] = "C:\\Code\\Nodinite.LogAgent.Log4NetAppender\\Nodinite.LogAgent.Log4NetAppender.TestClient\\Logs\\"; // Should "only" be set in config file
log4net.GlobalContext.Properties["SequenceNo"] = "0"; // This value should be set +1 before any Log operation

log4net.GlobalContext.Properties["ApplicationInterchangeId"] = "SAMPLE:ApplicationInterchangeId";
log4net.GlobalContext.Properties["OriginalMessageType"] = "SAMPLE:OriginalMessageType";
log4net.GlobalContext.Properties["LogAgentID"] = "42";
log4net.GlobalContext.Properties["EventDirection"] = "1";
log4net.GlobalContext.Properties["EventNumber"] = "1337";
log4net.GlobalContext.Properties["EndPointDirection"] = "1";
log4net.GlobalContext.Properties["EndPointName"] = "SAMPLE:EndPointName";
log4net.GlobalContext.Properties["EndPointUri"] = "SAMPLE:EndPointUri";
log4net.GlobalContext.Properties["ProcessingUser"] = "SAMPLE:ProcessingUser";
log4net.GlobalContext.Properties["ModuleType"] = "SAMPLE:ModuleType";
log4net.GlobalContext.Properties["ProcessName"] = "SAMPLE:ProcessName";
log4net.GlobalContext.Properties["ProcessingMachineName"] = "SAMPLE:ProcessingMachineName";
log4net.GlobalContext.Properties["ProcessingModuleType"] = "SAMPLE:ProcessingModuleType";
log4net.GlobalContext.Properties["ProcessingModuleName"] = "SAMPLE:ProcessingModuleName";
log4net.GlobalContext.Properties["ApplicationInterchangeId"] = "SAMPLE:ApplicationInterchangeId";
log4net.GlobalContext.Properties["LocalInterchangeId"] = "SAMPLE:LocalInterchangeId";
log4net.GlobalContext.Properties["ServiceInstanceActivityId"] = "SAMPLE:ServiceInstanceActivityId";

log4net.GlobalContext.Properties["Context"] = new Dictionary<string, string>
{
    { "Key1", "Value1" },
    { "Key2", "Value2" }
};
```

:fa-book: Please review the [JSON Log Event][] user guide for details about each entry.  

---

## :fa-hand-point-right: Next Steps

* :fa-code: [JSON Log Event][] - The format the appender sends to the Log API  
* :fa-tags: [Context Options][] - Add context properties to each event  
* :fa-arrows-left-right: [Event Direction][EventDirections] - Set the direction of each event  
* :fa-plug: [Endpoint Types][EndpointTypes] - Pick the [Endpoint][Endpoints] type for your events  

## :fa-link-horizontal: Related Topics

* :fa-cloud-arrow-down: [Log API][]  
* :fa-file-lines: [What is a Log Event?][Log Event]  
* :fa-sign-in-alt: [Endpoints][]  
* :fa-puzzle-piece: [Log4Net Appender][]  

[1]:{ndm}/Documentation%20Pictures/LogAgent/Log4NetAppender/nuget_install_log4net.png

[Context Options]:{ndr}/Core%20Services/Log%20Event/Features/Context%20Options.md
[Endpoint Directions]:{ndr}/Core%20Services/Log%20Event/Features/Endpoint%20Directions.md
[Endpoints]:{ndr}/Repository%20Model/Endpoints/Overview.md
[EndpointTypes]:{ndr}/Core%20Services/Log%20Event/Features/Endpoint%20Types.md
[EventDirections]:{ndr}/Core%20Services/Log%20Event/Features/Event%20Directions.md
[File Monitoring Agent]:{ndr}/Logging%20and%20Monitoring/File%20Folder/Overview.md
[JSON Log Event]:{ndr}/Core%20Services/Log%20Event/Features/JSON%20Log%20Event.md
[Log API]:{ndr}/Core%20Services/Log%20API/Overview.md
[Log Event]:{ndr}/Core%20Services/Log%20Event/Overview.md
[Log Views]:{ndr}/Administration/1.%20Log%20Management/1.%20Log%20Views/Features/What%20is%20a%20Log%20View.md
[Log4Net Appender]:{ndr}/Logging%20and%20Monitoring/Log4Net%20Appender/Overview.md
[Log4NetApache]:https://logging.apache.org/log4net/index.html
[Message Context Key]:{ndr}/Administration/1.%20Log%20Management/2.%20Search%20Fields/Features/Search%20Field%20Expressions/Message%20Context%20Key.md
[Pickup Service]:{ndr}/Logging%20and%20Monitoring/Pickup%20LogEvents%20Service/Overview.md
[Search Fields]:{ndr}/Administration/1.%20Log%20Management/2.%20Search%20Fields/Features/What%20is%20a%20Search%20Field.md
[Serilog]:{ndr}/Logging%20and%20Monitoring/Serilog/Overview.md
[Servers step]:{ndr}/Install%20and%20Update/Getting%20started/Version%207/Install%20Nodinite%20v7%20Steps/04%20-%20Servers.md#core-platform-services