Skip to main content

How to Log an Exception with the LoggerMessage Source Generator in C#

· 9 min read
Jagdish Kumawat
Founder @ Dewiride

To log an exception with a [LoggerMessage] method, give the method an Exception parameter and leave it out of the message. The source generator hands it to the logger as the entry's exception, and the console prints it under the message.

Microsoft's guide to compile-time logging: The source generator is triggered when LoggerMessageAttribute is used on partial logging methods. When triggered, it autogenerates the implementation of the partial methods it's decorating. An Exception parameter is one of the parameters it handles in a special way: As a general rule, the first instance of ILogger, LogLevel, and Exception are treated specially in the log method signature of the source generator. The exception doesn't fill a placeholder in the message. It goes to the logger separately, because The ILogger.Log signature accepts the LogLevel and optionally an Exception.

Syntax​

Syntax
static partial class <ClassName>
{
[LoggerMessage(EventId = <id>, Level = LogLevel.<level>, Message = "<text with {Placeholders}>")]
public static partial void <MethodName>(ILogger logger, Exception exception, <otherParameters>);
}

<ClassName>.<MethodName>(logger, exception, <otherArguments>);
PartWhat it is
static partial class <ClassName>The class that holds the logging methods. The guide: the consuming class and method need to be partial
<id>, <level>The event ID, a number for this kind of entry, and how serious it is, such as Error
MessageThe text, with a placeholder for each value, but none for the exception
ILogger loggerThe logger to write to. A static method takes it as a parameter: the ILogger instance must be passed as an argument
Exception exceptionThe exception. The generator passes it to the logger as the entry's exception
<otherParameters>The values for the placeholders, matched by name

You write no body for the method: the generator writes it when the project builds.

The Example​

A console app called LoggerMessageException logs that a file couldn't be printed because the printer is out of paper. The reason is an InvalidOperationException, and the log entry carries it.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n LoggerMessageException
cd LoggerMessageException
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/LoggerMessageException/LoggerMessageException.csproj:
Determining projects to restore...
Restored /Users/you/source/LoggerMessageException/LoggerMessageException.csproj (in 44 ms).
Restore succeeded.

dotnet new console -n LoggerMessageException creates a folder named LoggerMessageException with a project file and a Program.cs, and cd moves into it. This example also needs a NuGet package, the console logger, which Step 2 adds. Open the folder in VS Code, or LoggerMessageException.csproj in Visual Studio.

Step 2: Write the Code​

First add the console logger package, in the project folder:

Terminal
dotnet add package Microsoft.Extensions.Logging.Console --version 10.0.15
Output
info : X.509 certificate chain validation will use the fallback certificate bundle at '/usr/local/share/dotnet/sdk/10.0.404/trustedroots/codesignctl.pem'.
info : X.509 certificate chain validation will use the fallback certificate bundle at '/usr/local/share/dotnet/sdk/10.0.404/trustedroots/timestampctl.pem'.
info : Adding PackageReference for package 'Microsoft.Extensions.Logging.Console' into project '/Users/you/source/LoggerMessageException/LoggerMessageException.csproj'.
info : Restoring packages for /Users/you/source/LoggerMessageException/LoggerMessageException.csproj...
info : GET https://api.nuget.org/v3/vulnerabilities/index.json
info : OK https://api.nuget.org/v3/vulnerabilities/index.json 305ms
info : GET https://api.nuget.org/v3-vulnerabilities/2026.11.30.23.39.07/vulnerability.base.json
info : GET https://api.nuget.org/v3-vulnerabilities/2026.11.30.23.39.07/2026.11.30.23.39.07/vulnerability.update.json
info : OK https://api.nuget.org/v3-vulnerabilities/2026.11.30.23.39.07/vulnerability.base.json 325ms
info : OK https://api.nuget.org/v3-vulnerabilities/2026.11.30.23.39.07/2026.11.30.23.39.07/vulnerability.update.json 907ms
info : Package 'Microsoft.Extensions.Logging.Console' is compatible with all the specified frameworks in project '/Users/you/source/LoggerMessageException/LoggerMessageException.csproj'.
info : PackageReference for package 'Microsoft.Extensions.Logging.Console' version '10.0.15' added to file '/Users/you/source/LoggerMessageException/LoggerMessageException.csproj'.
info : Generating MSBuild file /Users/you/source/LoggerMessageException/obj/LoggerMessageException.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/you/source/LoggerMessageException/obj/project.assets.json
log : Restored /Users/you/source/LoggerMessageException/LoggerMessageException.csproj (in 2.05 sec).

dotnet add package adds a PackageReference to LoggerMessageException.csproj and restores the package. Microsoft.Extensions.Logging.Console writes log entries to the console. It depends on Microsoft.Extensions.Logging.Abstractions, which has ILogger, the [LoggerMessage] attribute and the source generator.

Then replace everything in Program.cs. First the logger:

Program.cs (the logger)
using Microsoft.Extensions.Logging;

using ILoggerFactory loggerFactory = LoggerFactory.Create(logging => logging.AddConsole());
ILogger logger = loggerFactory.CreateLogger("Printer");

LoggerFactory.Create sets up logging, AddConsole() sends the entries to the console, and CreateLogger("Printer") makes a logger whose category is Printer.

Then the exception and the call:

Program.cs (the exception and the call)
// An exception is an object. In an app, a catch block hands it to you;
// here new creates one, so it has no stack trace and the output stays short.
InvalidOperationException outOfPaper = new("The printer is out of paper.");

Log.PrintFailed(logger, outOfPaper, "invoice-42.pdf");

outOfPaper is an ordinary exception object. It's created with new and never thrown, so it has no stack trace to print; the FAQ shows a caught one. Log.PrintFailed gets the logger, the exception and the file name.

Last, the logging method:

Program.cs (the logging method)
static partial class Log
{
// The Exception parameter has no placeholder in the message:
// the generator passes it to the logger as the entry's exception.
[LoggerMessage(EventId = 1, Level = LogLevel.Error, Message = "Could not print {FileName}.")]
public static partial void PrintFailed(ILogger logger, Exception exception, string fileName);
}
  • Message = "Could not print {FileName}." has one placeholder, for the file name. The generator fills {FileName} from the fileName parameter.
  • Exception exception has no placeholder. The generator passes it to the logger as the entry's exception.
  • partial, with no body: the generator writes the method.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
fail: Printer[1]
Could not print invoice-42.pdf.
System.InvalidOperationException: The printer is out of paper.

macOS-style terminal window titled Terminal — LoggerMessageException showing dotnet run printing an error entry for the Printer category with event ID 1, the message Could not print invoice-42.pdf. and, on the line below it, System.InvalidOperationException: The printer is out of paper.

The entry has three parts:

  • fail: Printer[1]: the level, fail for an error, then the category and the event ID.
  • Could not print invoice-42.pdf.: the message, with {FileName} filled in.
  • System.InvalidOperationException: The printer is out of paper.: the exception, on its own line under the message, with its type and its message.

The exception never appeared in the message text: the generator sent it to the logger on its own, and the console logger printed it.

The Complete Files​

macOS-style code window titled Program.cs — LoggerMessageException showing a console logger factory, a logger named Printer, an InvalidOperationException created with new, a call to Log.PrintFailed with the logger, the exception and invoice-42.pdf, and a static partial class Log with a LoggerMessage method that takes an ILogger, an Exception and a file name

Program.cs
using Microsoft.Extensions.Logging;

using ILoggerFactory loggerFactory = LoggerFactory.Create(logging => logging.AddConsole());
ILogger logger = loggerFactory.CreateLogger("Printer");

// An exception is an object. In an app, a catch block hands it to you;
// here new creates one, so it has no stack trace and the output stays short.
InvalidOperationException outOfPaper = new("The printer is out of paper.");

Log.PrintFailed(logger, outOfPaper, "invoice-42.pdf");

static partial class Log
{
// The Exception parameter has no placeholder in the message:
// the generator passes it to the logger as the entry's exception.
[LoggerMessage(EventId = 1, Level = LogLevel.Error, Message = "Could not print {FileName}.")]
public static partial void PrintFailed(ILogger logger, Exception exception, string fileName);
}
LoggerMessageException.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="10.0.15" />
</ItemGroup>

</Project>

Common Mistakes​

MistakeWhat happensDo this instead
A placeholder for the exception in the messageWith Message = "Could not print {FileName}: {Exception}", the build warned warning SYSLIB1013: Don't include a template for exception in the logging message since it is implicitly taken care of, and the console printed the exception twice: inside the message and under itLeave the exception out of the message. The SYSLIB1013 page: the first exception is passed down to the logging infrastructure explicitly. It doesn't need to be repeated in the logging message.
Logging only exception.MessageWith a string error parameter filled from outOfPaper.Message, the console printed Could not print invoice-42.pdf: The printer is out of paper. and nothing else: the entry had no exception, so its type was lostPass the Exception object itself, as the example does

FAQ​

Why does Microsoft's article name SYSLIB0025 for this warning?​

It's a mistake in that article. Its example with an exception placeholder in the message says the build reports SYSLIB0025, but the same example builds with warning SYSLIB1013, as this guide's build did. SYSLIB0025 is a different warning, about an obsolete attribute. I reported it to the .NET docs as issue #57059.

What does the console print for an exception that was thrown?​

Its stack trace as well. In a catch block, int.Parse("forty-two") threw a FormatException, and a [LoggerMessage] method like this one printed the message, the exception's type and message, and then one line per method call, such as at System.Int32.Parse(String s), down to the line of the program that called int.Parse, with its file and line number. What gets printed is up to each logger: Exception logging is provider-specific.

Can the exception be null?​

Yes, when the parameter is Exception?. Passing null printed only fail: Printer[1] and Could not print invoice-42.pdf., with no exception line. One method can then log the same event with or without an exception.

Do I have to set EventId?​

No. Without EventId, the same call printed fail: Printer[569136707]: the entry still got an event ID, but not one the code chose. Set EventId to keep IDs that you pick.

Conclusion​

Give a [LoggerMessage] method an Exception parameter and leave it out of the message. The generator passes it to the logger as the entry's exception, and the console prints it under the message, with a stack trace when it was thrown and caught.

Additional Resources​