---
title: "How to manage logging in C#"  
description: "How to manage logging in C#"  
author: "ICSM Computer"  
published: 2025-04-24  
updated: 2025-04-24  
canonical: https://www.mindstick.com/interview/34073/how-to-manage-logging-in-c-sharp  
category: "c#"  
tags: ["c#", ".net"]  
reading_time: 4 minutes  

---

# How to manage logging in C#

Logging in C# can be managed in various ways depending on the size, complexity, and environment of your application (e.g., console app, ASP.NET, etc.). Here's a breakdown of the most common approaches and tools:

### 1. Built-in Logging with `Microsoft.Extensions.Logging` (Recommended for ASP.NET Core / .NET Core)

**Setup:** Add the NuGet package:

```plaintext
dotnet add package Microsoft.Extensions.Logging
```

## Example:

```cs
using Microsoft.Extensions.Logging;

public class MyService
{
    private readonly ILogger<MyService> _logger;

    public MyService(ILogger<MyService> logger)
    {
        _logger = logger;
    }

    public void DoSomething()
    {
        _logger.LogInformation("Doing something at {Time}", DateTime.UtcNow);
        _logger.LogWarning("This is a warning.");
        _logger.LogError("This is an error.");
    }
}
```

## Available log levels:

1. `LogTrace`
2. `LogDebug`
3. `LogInformation`
4. `LogWarning`
5. `LogError`
6. `LogCritical`

### 2. `log4net` (Great for legacy ASP.NET MVC 5 or WinForms/WPF)

**Setup:** Add via NuGet:

```plaintext
Install-Package log4net
```

## Basic Configuration (log4net.config):

```xml
<log4net>
  <appender name="FileAppender" type="log4net.Appender.FileAppender">
    <file value="log.txt" />
    <appendToFile value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="INFO" />
    <appender-ref ref="FileAppender" />
  </root>
</log4net>
```

## Usage:

```cs
private static readonly ILog log = LogManager.GetLogger(typeof(MyClass));

public void DoWork()
{
    log.Info("Doing work...");
    log.Error("Something went wrong!");
}
```

### 3. `NLog` (Flexible and very powerful for .NET Framework and .NET Core)

## Setup:

```plaintext
Install-Package NLog
Install-Package NLog.Web.AspNetCore  // if using in ASP.NET Core
```

## Basic config (nlog.config):

```xml
<nlog>
  <targets>
    <target name="logfile" xsi:type="File" fileName="file.txt" />
  </targets>
  <rules>
    <logger name="*" minlevel="Info" writeTo="logfile" />
  </rules>
</nlog>
```

## Usage:

```cs
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

public void Run()
{
    logger.Info("Running...");
    logger.Error("Error occurred!");
}
```

### 4. Simple Console/File Logger for Small Apps

```cs
public static class Logger
{
    public static void Log(string message)
    {
        var logMessage = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}";
        Console.WriteLine(logMessage);
        File.AppendAllText("log.txt", logMessage + Environment.NewLine);
    }
}
```

### Tips for Effective Logging

1. Use structured logging (e.g., `LogInformation("User {UserId} logged in", userId);`)
2. Avoid excessive logging in performance-critical areas.
3. Always log exceptions with `ex.ToString()` for stack trace visibility.
4. Use log rotation and archiving for file-based logs.
5. Use log viewers (like Seq or Kibana) for better analysis.

Want help setting this up for your specific project (e.g., ASP.NET MVC 5 or Core)?

## Answers

### Answer by ICSM Computer

Logging in C# can be managed in various ways depending on the size, complexity, and environment of your application (e.g., console app, ASP.NET, etc.). Here's a breakdown of the most common approaches and tools:

### 1. Built-in Logging with `Microsoft.Extensions.Logging` (Recommended for ASP.NET Core / .NET Core)

**Setup:** Add the NuGet package:

```plaintext
dotnet add package Microsoft.Extensions.Logging
```

## Example:

```cs
using Microsoft.Extensions.Logging;

public class MyService
{
    private readonly ILogger<MyService> _logger;

    public MyService(ILogger<MyService> logger)
    {
        _logger = logger;
    }

    public void DoSomething()
    {
        _logger.LogInformation("Doing something at {Time}", DateTime.UtcNow);
        _logger.LogWarning("This is a warning.");
        _logger.LogError("This is an error.");
    }
}
```

## Available log levels:

1. `LogTrace`
2. `LogDebug`
3. `LogInformation`
4. `LogWarning`
5. `LogError`
6. `LogCritical`

### 2. `log4net` (Great for legacy ASP.NET MVC 5 or WinForms/WPF)

**Setup:** Add via NuGet:

```plaintext
Install-Package log4net
```

## Basic Configuration (log4net.config):

```xml
<log4net>
  <appender name="FileAppender" type="log4net.Appender.FileAppender">
    <file value="log.txt" />
    <appendToFile value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="INFO" />
    <appender-ref ref="FileAppender" />
  </root>
</log4net>
```

## Usage:

```cs
private static readonly ILog log = LogManager.GetLogger(typeof(MyClass));

public void DoWork()
{
    log.Info("Doing work...");
    log.Error("Something went wrong!");
}
```

### 3. `NLog` (Flexible and very powerful for .NET Framework and .NET Core)

## Setup:

```plaintext
Install-Package NLog
Install-Package NLog.Web.AspNetCore  // if using in ASP.NET Core
```

## Basic config (nlog.config):

```xml
<nlog>
  <targets>
    <target name="logfile" xsi:type="File" fileName="file.txt" />
  </targets>
  <rules>
    <logger name="*" minlevel="Info" writeTo="logfile" />
  </rules>
</nlog>
```

## Usage:

```cs
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

public void Run()
{
    logger.Info("Running...");
    logger.Error("Error occurred!");
}
```

### 4. Simple Console/File Logger for Small Apps

```cs
public static class Logger
{
    public static void Log(string message)
    {
        var logMessage = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}";
        Console.WriteLine(logMessage);
        File.AppendAllText("log.txt", logMessage + Environment.NewLine);
    }
}
```

### Tips for Effective Logging

1. Use structured logging (e.g., `LogInformation("User {UserId} logged in", userId);`)
2. Avoid excessive logging in performance-critical areas.
3. Always log exceptions with `ex.ToString()` for stack trace visibility.
4. Use log rotation and archiving for file-based logs.
5. Use log viewers (like Seq or Kibana) for better analysis.

Want help setting this up for your specific project (e.g., ASP.NET MVC 5 or Core)?


---

Original Source: https://www.mindstick.com/interview/34073/how-to-manage-logging-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
