IC Improve Code Recipes

Recipe 4.5 · C#

Replacing the Homegrown LogHelper

Problem

The code base has a static LogHelper with 1,500 call sites. It writes to a text file, sometimes to a database table, and catches every exception it hits. You want ILogger everywhere, but you cannot change 1,500 lines in one release, and many of the callers are static utility methods with no constructor to inject into.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not this: the classic LogHelper.
public static class LogHelper
{
    public static void Error(string msg, Exception ex)
    {
        try
        {
            string path = ConfigurationManager.AppSettings["LogPath"];
            File.AppendAllText(path, DateTime.Now + " ERROR " + msg +
                " " + ex.Message + Environment.NewLine);
        }
        catch { }
    }

    public static void Info(string msg) { /* same again */ }
}

The improved recipe

Keep the class name and the method signatures, and turn the body into a thin adapter over ILoggerFactory. Mark the methods obsolete so the compiler lists every call site you still have to migrate.

C#
using System;
using System.IO;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;

namespace ImproveCode.Logging;

/// <summary>
/// Transitional adapter. Existing call sites keep compiling while
/// they move to injected ILogger&lt;T&gt;.
/// </summary>
public static class LogHelper
{
    private const string Migrate =
        "Inject ILogger<T> instead of calling LogHelper.";

    private static ILoggerFactory _factory =
        NullLoggerFactory.Instance;

    public static void Initialize(ILoggerFactory factory)
    {
        ArgumentNullException.ThrowIfNull(factory);
        _factory = factory;
    }

    [Obsolete(Migrate)]
    public static void Info(
        string message,
        [CallerFilePath] string file = "",
        [CallerMemberName] string member = "")
    {
        For(file).LogInformation(
            "{Message} ({Member})", message, member);
    }

    [Obsolete(Migrate)]
    public static void Warn(
        string message,
        [CallerFilePath] string file = "",
        [CallerMemberName] string member = "")
    {
        For(file).LogWarning(
            "{Message} ({Member})", message, member);
    }

    [Obsolete(Migrate)]
    public static void Error(
        string message,
        Exception? ex = null,
        [CallerFilePath] string file = "",
        [CallerMemberName] string member = "")
    {
        For(file).LogError(
            ex, "{Message} ({Member})", message, member);
    }

    // Uses the calling file name as the category, so filtering
    // by class still works for legacy callers.
    private static ILogger For(string file)
    {
        string category = string.IsNullOrEmpty(file)
            ? "Legacy"
            : "Legacy." + Path.GetFileNameWithoutExtension(file);
        return _factory.CreateLogger(category);
    }
}

At startup, as a usage snippet:

C#
WebApplication app = builder.Build();
LogHelper.Initialize(app.Services.GetRequiredService<ILoggerFactory>());

How it works

Every old call now flows into the same pipeline as new code: Serilog, the correlation scope, level filtering, the JSON file. You get the benefits on day one without editing a single caller.

The compiler fills in [CallerFilePath] and [CallerMemberName] at each call site, so a call from InvoiceService.cs logs under the category Legacy.InvoiceService with the method name attached. The old text file never told you that.

[Obsolete] turns every remaining call into a build warning. The warning count becomes your migration progress bar, and new code that reaches for LogHelper is flagged in review.

The migration I use:

  1. Replace the body of the existing LogHelper with the adapter, keeping public signatures.
  2. Call Initialize at startup in every host (web app, service, console tools).
  3. Delete the old log file writer and any catch { } inside the logging code.
  4. Move classes to injected ILogger<T> when you touch them for other reasons.
  5. When the warning count reaches zero, delete LogHelper.

Variations and pitfalls

  • If the old helper had overloads such as Error(Exception ex) or Debug(string), keep them. The point is that no caller has to change yet.
  • Before Initialize runs, the null factory drops messages. If you have static constructors that log, either initialize earlier or accept that those few lines go nowhere.
  • If the old helper wrote to a database table that a support screen reads, keep that table as a separate sink (Serilog has an MS SQL Server sink) until the screen is retired. Don't break the support team's workflow during a refactor.
  • Resist adding new features to the adapter. It exists to be deleted.

On .NET Framework

The same adapter works on .NET Framework 4.6.2 and later with the Microsoft.Extensions.Logging package. Build a factory in Application_Start with LoggerFactory.Create(b => b.AddSerilog()) (from Serilog.Extensions.Logging) and pass it to Initialize.