IC Improve Code Recipes

Recipe 4.6 · C#

Logging in Console Apps and Windows Services

Problem

Scheduled console tools and Windows services fail where nobody is watching. Output goes to Console.WriteLine, which disappears when Task Scheduler runs the job. Unhandled exceptions end the process with a bare exit code. Each run's lines blur into the previous run's, so you cannot tell which import processed which file.

The way it's often written

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

C#
// Not this: no host, no structure, and failures vanish.
static void Main(string[] args)
{
    Console.WriteLine("Starting import " + DateTime.Now);
    try
    {
        new Importer().Run();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    Console.WriteLine("Done");
}

The improved recipe

Use the generic host so console tools get the same configuration and logging pipeline as web apps. Open a scope per run, time every run, and return a non-zero exit code on failure.

C#
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ImproveCode.Logging;
using Serilog;
using Serilog.Formatting.Compact;

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .CreateBootstrapLogger();

try
{
    HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);

    builder.Services.AddSerilog((services, log) => log
        .ReadFrom.Configuration(builder.Configuration)
        .Enrich.FromLogContext()
        .WriteTo.Console()
        .WriteTo.File(
            new CompactJsonFormatter(),
            System.IO.Path.Combine(AppContext.BaseDirectory,
                "logs", "import-.json"),
            rollingInterval: RollingInterval.Day,
            retainedFileCountLimit: 30));

    builder.Services.AddHostedService<ImportWorker>();

    using IHost host = builder.Build();
    await host.RunAsync();
    return 0;
}
catch (Exception ex)
{
    Log.Fatal(ex, "Host terminated unexpectedly");
    return 1;
}
finally
{
    await Log.CloseAndFlushAsync();
}

The worker opens a scope with a run ID and logs one start line and one end line per run:

C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace ImproveCode.Logging;

public sealed class ImportWorker(ILogger<ImportWorker> logger)
    : BackgroundService
{
    private static readonly TimeSpan Interval = TimeSpan.FromHours(1);

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(Interval);

        do
        {
            await RunOnceAsync(stoppingToken);
        }
        while (await timer.WaitForNextTickAsync(stoppingToken));
    }

    private async Task RunOnceAsync(CancellationToken ct)
    {
        string runId = Guid.NewGuid().ToString("N")[..8];
        var scope = new Dictionary<string, object> { ["RunId"] = runId };

        using (logger.BeginScope(scope))
        {
            var clock = Stopwatch.StartNew();
            logger.LogInformation("Import run started");

            try
            {
                int rows = await ImportAsync(ct);
                logger.LogInformation(
                    "Import run finished: {Rows} rows in {ElapsedMs} ms",
                    rows, clock.ElapsedMilliseconds);
            }
            catch (OperationCanceledException)
                when (ct.IsCancellationRequested)
            {
                logger.LogWarning("Import run cancelled by shutdown");
            }
            catch (Exception ex)
            {
                logger.LogError(ex,
                    "Import run failed after {ElapsedMs} ms",
                    clock.ElapsedMilliseconds);
            }
        }
    }

    private static async Task<int> ImportAsync(CancellationToken ct)
    {
        await Task.Delay(TimeSpan.FromSeconds(1), ct); // real work here
        return 0;
    }
}

How it works

Host.CreateApplicationBuilder gives a console app appsettings.json, environment variables, dependency injection and ILogger with the same conventions as ASP.NET Core. The Serilog setup is nearly identical to Recipe 4.2, so operations sees one log format across every host you deploy.

The file path is built from AppContext.BaseDirectory. Task Scheduler and the Service Control Manager start processes with a working directory of C:\Windows\System32, which is where relative log paths end up if you don't anchor them.

The RunId scope tags every line of one run, including lines from repositories and HTTP clients deep in the call stack. Searching for one run ID shows exactly what that run did. The start and finish lines with a row count and elapsed time are the two lines I read first every time: they tell me whether the job ran, whether it finished and whether it did a normal amount of work.

The worker catches exceptions per run and keeps going, because one bad file should not stop tomorrow's import. The outer try in Program.cs catches what escapes the host, writes it as Fatal, flushes, and returns exit code 1 so Task Scheduler or a monitoring agent can alert.

Variations and pitfalls

  • For a one-shot tool that runs and exits, skip the hosted service. Resolve your job class from host.Services, run it, and return its result as the exit code.
  • To run the same code as a Windows service, add Microsoft.Extensions.Hosting.WindowsServices and call builder.Services.AddWindowsService(). Chapter 14 covers the service details.
  • The Windows Event Log is a poor primary log, but writing Fatal events there as well (with the Serilog.Sinks.EventLog package) means server monitoring tools notice a crashed service.
  • For a tiny utility without a host, LoggerFactory.Create(b => b.AddSimpleConsole()) gives you ILogger in two lines. Dispose the factory before exit so output is flushed.
  • Don't let a BackgroundService exception escape ExecuteAsync. Since .NET 6, the default is to stop the host, which is usually right, but it should be your decision, made with a log line.