log4net
logging
machine name
C# programming
.NET logging

How do you log the machine name via log4net?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Logging the machine name is useful when the same application runs on multiple servers, containers, or desktop clients. In log4net, the most reliable approach is to add the machine name as a context property and include that property in the layout pattern. That keeps the value explicit and portable across appenders.

Set a Global Machine-Name Property

The simplest pattern is to assign Environment.MachineName once at startup.

csharp
1using System;
2using log4net;
3using log4net.Config;
4using log4net.Util;
5
6[assembly: XmlConfigurator(Watch = true)]
7
8public static class LoggingBootstrap
9{
10    public static void Configure()
11    {
12        GlobalContext.Properties["MachineName"] = Environment.MachineName;
13    }
14}

Call LoggingBootstrap.Configure() before writing your first log entry.

Add the Property to the Layout Pattern

Once the property exists, reference it from the appender layout.

xml
1<log4net>
2  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
3    <file value="logs/app.log" />
4    <appendToFile value="true" />
5    <rollingStyle value="Size" />
6    <maximumFileSize value="10MB" />
7    <maxSizeRollBackups value="5" />
8    <layout type="log4net.Layout.PatternLayout">
9      <conversionPattern value="%date %-5level [%property{MachineName}] %logger - %message%newline" />
10    </layout>
11  </appender>
12
13  <root>
14    <level value="INFO" />
15    <appender-ref ref="RollingFile" />
16  </root>
17</log4net>

Now each log line includes the machine name inside square brackets.

Example End-to-End Use

csharp
1using log4net;
2
3class Program
4{
5    private static readonly ILog Log = LogManager.GetLogger(typeof(Program));
6
7    static void Main()
8    {
9        LoggingBootstrap.Configure();
10        Log.Info("Application started");
11    }
12}

This is enough for file, console, and many other appenders because the property is resolved by the layout.

Why Use a Property Instead of Hardcoding Layout Logic

Context properties are better than embedding machine-name logic inside every log statement because:

  1. the value is defined once
  2. layout controls where it appears
  3. appenders can reuse the same metadata

That separation keeps application logging code focused on events, not formatting.

Useful Variations

If you want different scopes, log4net offers different contexts:

  • 'GlobalContext for application-wide values'
  • 'ThreadContext for per-thread values'
  • 'LogicalThreadContext for async-flow values'

Machine name belongs in GlobalContext because it is stable for the process lifetime.

Structured Appenders and Remote Shipping

If logs are shipped to a central system, machine name becomes even more valuable. The same application version running on six hosts can then be filtered by server during incident response.

For appenders that write to databases or remote collectors, include the same property in the mapped fields rather than only in plain text output.

Container and Cloud Naming Considerations

In containerized deployments, Environment.MachineName may represent the container host name rather than a long-lived physical server. That is still often useful, but you should decide whether you want:

  • machine name
  • container or pod name
  • deployment instance id

If your operations team needs a different identity, populate another global property beside machine name instead of overloading the same field.

Test the Configuration

Verify that the property is present before relying on it in production.

csharp
Log.Info("Machine-name test entry");

Then inspect the resulting log line and confirm it contains the expected host name. This catches startup-order mistakes where logging begins before the property is assigned.

Common Pitfalls

  • Setting the machine-name property after the first logs are already written.
  • Using ThreadContext for machine name instead of GlobalContext.
  • Adding the property in code but forgetting to reference it in the layout pattern.
  • Hardcoding machine names in config for environments that scale dynamically.
  • Assuming every central log system extracts host information automatically.

Summary

  • In log4net, the cleanest machine-name solution is a global context property.
  • Set GlobalContext.Properties["MachineName"] once at startup.
  • Reference it in the appender layout with %property{MachineName}.
  • Keep machine identity separate from individual log-message text.
  • Validate the first emitted log lines so startup order does not hide the field.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.