diff --git a/docs/core/extensions/logging/custom-provider.md b/docs/core/extensions/logging/custom-provider.md index ab770f44b7be3..0aeb14fbf06fb 100644 --- a/docs/core/extensions/logging/custom-provider.md +++ b/docs/core/extensions/logging/custom-provider.md @@ -1,44 +1,41 @@ --- title: Implement a custom logging provider description: Discover how to implement a custom logging provider with colorized logs, writing custom C# ILogger and ILoggerProvider implementations. -ms.date: 10/20/2025 +ms.date: 02/04/2026 ms.topic: how-to --- # Implement a custom logging provider in .NET -There are many [logging providers](providers.md) available for common logging needs. You might need to implement a custom when one of the available providers doesn't suit your application needs. In this article, you learn how to implement a custom logging provider that can be used to colorize logs in the console. +There are many [logging providers](providers.md) available for common logging needs. But you might need to implement a custom when one of the available providers doesn't suit your application needs. In this article, you learn how to implement a custom logging provider that can be used to colorize logs in the console. > [!TIP] -> The custom logging provider example source code is available in the **Docs GitHub repo**. For more information, see [GitHub: .NET Docs - Console Custom Logging](https://github.com/dotnet/docs/tree/main/docs/core/extensions/snippets/configuration/console-custom-logging). +> The custom logging provider example source code is available in the [docs GitHub repo](https://github.com/dotnet/docs/tree/main/docs/core/extensions/snippets/configuration/console-custom-logging). -### Sample custom logger configuration +## Sample custom logger configuration -The sample creates different color console entries per log level and event ID using the following configuration type: +The sample logger creates different color console entries per log level and event ID using the following configuration type: :::code language="csharp" source="../snippets/configuration/console-custom-logging/ColorConsoleLoggerConfiguration.cs"::: -The preceding code sets the default level to `Information`, the color to `Green`, and the `EventId` is implicitly `0`. +The preceding code sets the default color for the `Information` level to `Green`. The `EventId` is implicitly 0. -### Create the custom logger +## Create the custom logger -The `ILogger` implementation category name is typically the logging source. For example, the type where the logger is created: +The following code snippet shows the `ILogger` implementation: :::code language="csharp" source="../snippets/configuration/console-custom-logging/ColorConsoleLogger.cs"::: -The preceding code: +Each logger instance is instantiated by passing a category name, which is typically the type where the logger is created. The `IsEnabled` method checks `getCurrentConfig().LogLevelToColorMap.ContainsKey(logLevel)` to see if the requested log level is enabled (that is, in the configuration's dictionary of log levels). -- Creates a logger instance per category name. -- Checks `_getCurrentConfig().LogLevelToColorMap.ContainsKey(logLevel)` in `IsEnabled`, so each `logLevel` has a unique logger. In this implementation, each log level requires an explicit configuration entry to log. +It's a good practice to call within implementations since `Log` can be called by any consumer, and there are no guarantees that it was previously checked. The `IsEnabled` method should be very fast in most implementations. -It's a good practice to call within implementations since `Log` can be called by any consumer, and there are no guarantees that it was previously checked. The `IsEnabled` method should be very fast in most implementations. +:::code language="csharp" source="../snippets/configuration/console-custom-logging/ColorConsoleLogger.cs" range="20-23"::: -:::code language="csharp" source="../snippets/configuration/console-custom-logging/ColorConsoleLogger.cs" range="15-16"::: - -The logger is instantiated with the `name` and a `Func`, which returns the current config—this handles updates to the config values as monitored through the callback. +The logger is instantiated with the `name` and a `Func` that returns the current configuration. > [!IMPORTANT] -> The implementation checks if the `config.EventId` value is set. When `config.EventId` is not set or when it matches the exact `logEntry.EventId`, the logger logs in color. +> The implementation checks if the `config.EventId` value is set. When `config.EventId` is not set or when it matches the exact `logEntry.EventId`, the logger logs in color. ## Custom logger provider @@ -46,13 +43,11 @@ The `ILoggerProvider` object is responsible for creating logger instances. It's :::code language="csharp" source="../snippets/configuration/console-custom-logging/ColorConsoleLoggerProvider.cs"::: -In the preceding code, creates a single instance of the `ColorConsoleLogger` per category name and stores it in the [`ConcurrentDictionary`](/dotnet/api/system.collections.concurrent.concurrentdictionary-2). Additionally, the interface is required to update changes to the underlying `ColorConsoleLoggerConfiguration` object. - -To control the configuration of the `ColorConsoleLogger`, you define an alias on its provider: +In the preceding code, creates a single instance of the `ColorConsoleLogger` per category name and stores it in the [`ConcurrentDictionary`](/dotnet/api/system.collections.concurrent.concurrentdictionary-2). -:::code language="csharp" source="../snippets/configuration/console-custom-logging/ColorConsoleLoggerProvider.cs" range="6-8" highlight="6-7"::: +The `ColorConsoleLoggerProvider` class is decorated with two attributes: -The `ColorConsoleLoggerProvider` class defines two class-scoped attributes: +:::code language="csharp" source="../snippets/configuration/console-custom-logging/ColorConsoleLoggerProvider.cs" range="6-8"::: - : The `ColorConsoleLogger` type is _not supported_ in the `"browser"`. - : Configuration sections can define options using the `"ColorConsole"` key. @@ -61,34 +56,25 @@ The configuration can be specified with any valid [configuration provider](../co :::code language="json" source="../snippets/configuration/console-custom-logging/appsettings.json"::: -This configures the log levels to the following values: - -- : -- : -- : - -The log level is set to , which overrides the default value set in the `ColorConsoleLoggerConfiguration` object. +The _appsettings.json_ file specifies that the color for the log level is , which overrides the default value set in the `ColorConsoleLoggerConfiguration` object. ## Usage and registration of the custom logger -By convention, registering services for dependency injection happens as part of the startup routine of an application. The registration occurs in the `Program` class, or could be delegated to a `Startup` class. In this example, you'll register directly from the _Program.cs_. - -To add the custom logging provider and corresponding logger, add an with from the : +By convention, services are registered for dependency injection as part of the startup routine of an application. In this example, the logging service is registered directly from the _Program.cs_ file. -:::code language="csharp" source="../snippets/configuration/console-custom-logging/Program.cs" highlight="6-14"::: +To add the custom logging provider and corresponding logger, add an by calling a custom extension method, `AddColorConsoleLogger`, on the from the property: -The `ILoggingBuilder` creates one or more `ILogger` instances. The `ILogger` instances are used by the framework to log the information. - -The configuration from the _appsettings.json_ file overrides the following values: - -- : -- : +:::code language="csharp" source="../snippets/configuration/console-custom-logging/Program.cs" highlight="8-16"::: By convention, extension methods on `ILoggingBuilder` are used to register the custom provider: :::code language="csharp" source="../snippets/configuration/console-custom-logging/Extensions/ColorConsoleLoggerExtensions.cs"::: -Running this simple application will render color output to the console window similar to the following image: +The `ILoggingBuilder` creates one or more `ILogger` instances. The `ILogger` instances are used by the framework to log the information. + +The instantiation code overrides the color values from the _appsettings.json_ file for and . + +When you run this simple app, it renders color output to the console window similar to the following image: :::image type="content" source="media/color-console-logger.png" alt-text="Color console logger sample output"::: diff --git a/docs/core/extensions/snippets/configuration/console-custom-logging/ColorConsoleLogger.cs b/docs/core/extensions/snippets/configuration/console-custom-logging/ColorConsoleLogger.cs index a7884c99d7530..df51ad49e026d 100644 --- a/docs/core/extensions/snippets/configuration/console-custom-logging/ColorConsoleLogger.cs +++ b/docs/core/extensions/snippets/configuration/console-custom-logging/ColorConsoleLogger.cs @@ -4,7 +4,8 @@ public sealed class ColorConsoleLogger( string name, Func getCurrentConfig) : ILogger { - public IDisposable? BeginScope(TState state) where TState : notnull => default!; + public IDisposable? BeginScope(TState state) + where TState : notnull => default!; public bool IsEnabled(LogLevel logLevel) => getCurrentConfig().LogLevelToColorMap.ContainsKey(logLevel); diff --git a/docs/core/extensions/snippets/configuration/console-custom-logging/Program.cs b/docs/core/extensions/snippets/configuration/console-custom-logging/Program.cs index 6f79ee3f22a62..e2d74fa7eb2a8 100644 --- a/docs/core/extensions/snippets/configuration/console-custom-logging/Program.cs +++ b/docs/core/extensions/snippets/configuration/console-custom-logging/Program.cs @@ -7,15 +7,17 @@ builder.Logging.ClearProviders(); builder.Logging.AddColorConsoleLogger(configuration => { - // Replace warning value from appsettings.json of "Cyan" - configuration.LogLevelToColorMap[LogLevel.Warning] = ConsoleColor.DarkCyan; - // Replace warning value from appsettings.json of "Red" - configuration.LogLevelToColorMap[LogLevel.Error] = ConsoleColor.DarkRed; + // Replace value of "Cyan" from appsettings.json. + configuration.LogLevelToColorMap[LogLevel.Warning] + = ConsoleColor.DarkCyan; + // Replace value of "Red" from appsettings.json. + configuration.LogLevelToColorMap[LogLevel.Error] + = ConsoleColor.DarkRed; }); using IHost host = builder.Build(); -var logger = host.Services.GetRequiredService>(); +ILogger logger = host.Services.GetRequiredService>(); logger.LogDebug(1, "Does this line get hit?"); // Not logged logger.LogInformation(3, "Nothing to see here."); // Logs in ConsoleColor.DarkGreen