C# Reference ยท Exceptions and Diagnostics
C# logging with ILogger
Reference for Microsoft.Extensions.Logging in C#: ILogger, ILoggerFactory, log levels, message templates, scopes, LoggerMessage and filtering.
Microsoft.Extensions.Logging is the logging abstraction used by ASP.NET Core, the generic host and most .NET libraries. Your code writes to an ILogger (usually an ILogger<T> injected into a constructor) and the application decides where the messages go by registering providers: console, debug window, files, a cloud service.
A message has a level, a category (normally the class name), an optional event id, and a message template such as "Order {OrderId} shipped". The named placeholders are kept as structured data, so a provider can store OrderId as a field instead of only a string.
logger.LogInformation("Order {OrderId} shipped to {City}", orderId, city);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public interface ILogger { void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter); bool IsEnabled(LogLevel logLevel); IDisposable? BeginScope<TState>(TState state) where TState : notnull; } // Extension methods in LoggerExtensions logger.LogInformation(string? message, params object?[] args); logger.LogError(Exception? exception, string? message, params object?[] args); logger.Log(LogLevel level, EventId eventId, Exception? ex, string? message, params object?[] args);
| Name | Description |
|---|---|
LogLevel |
Trace (0), Debug, Information, Warning, Error, Critical, and None (6, only for filters). |
EventId |
A numeric id plus an optional name that identifies a kind of message. |
message |
A message template. Placeholders are matched to args by position, not by name. |
exception |
Optional exception attached to the entry; providers print it with its stack trace. |
ILogger<T> |
A logger whose category is the full name of T. |
ILoggerFactory.CreateLogger(name) |
Creates a logger for any category string. |
Returns: the logging methods return void; BeginScope returns an IDisposable that ends the scope.
Errors: logging itself should not throw. A provider that throws has its exception collected and rethrown as an AggregateException by the factory call, so a broken provider can still break your code. Format errors in a template (for example more placeholders than arguments) surface as a FormatException when the message is formatted.
Usage notes
- Use templates, not interpolation.
LogInformation("User {Id}", id)keepsIdas data and does no string work when the level is off.LogInformation($"User {id}")always builds a string and loses the structure. - Placeholders are positional. The first argument fills the first placeholder whatever its name. Names matter only to providers that store structured data.
- The minimum level is checked first. Entries below it are discarded before formatting. Use
IsEnabledto skip expensive argument preparation. - Prefer
LoggerMessage.LoggerMessage.Defineor the[LoggerMessage]source generator avoid boxing and re-parsing the template on every call. The generator needs a source generator step, which our runner does not have, so the delegate form is shown here. - Pass the exception as the first argument (
LogError(ex, "...")), not inside the text, so providers can print the full details. - Scopes attach context (a request id) to every entry written while they are open. A provider has to opt in: the built-in console provider needs
IncludeScopes = true, and a custom provider implementsISupportExternalScope. - Never log secrets or personal data.
TraceandDebugmessages in particular often contain values you would not want in a file. - Without a host build a factory with
LoggerFactory.Createand dispose it so buffered entries are flushed.