diff --git a/docs/core/enrichment/application-log-enricher.md b/docs/core/enrichment/application-log-enricher.md new file mode 100644 index 0000000000000..2bf801420aecf --- /dev/null +++ b/docs/core/enrichment/application-log-enricher.md @@ -0,0 +1,141 @@ +--- +title: Application log enricher +description: Learn how to use the application log enricher to add application-specific information to your telemetry in .NET. +ms.date: 10/14/2025 +--- + +# Application log enricher + +The application log enricher augments telemetry logs with application-specific information such as service host details and application metadata. This enricher provides essential context about your application's deployment environment, version information, and service identity that helps with monitoring, debugging, and operational visibility. + +You can register the enrichers in an IoC container, and all registered enrichers are automatically picked up by respective telemetry logs, where they enrich the telemetry information. + +## Prerequisites + +To function properly, this enricher requires that [application metadata](application-metadata.md) is configured and available. The application metadata provides the foundational information that the enricher uses to populate telemetry dimensions. + +## Install the package + +To get started, install the [📦 Microsoft.Extensions.Telemetry](https://www.nuget.org/packages/Microsoft.Extensions.Telemetry) NuGet package: + +### [.NET CLI](#tab/dotnet-cli) + +```dotnetcli +dotnet add package Microsoft.Extensions.Telemetry +``` + +Or, if you're using .NET 10+ SDK: + +```dotnetcli +dotnet package add Microsoft.Extensions.Telemetry +``` + +### [PackageReference](#tab/package-reference) + +```xml + +``` + +--- + +## Application log enricher + +The application log enricher provides application-specific enrichment. The log enricher specifically targets log telemetry and adds standardized dimensions that help identify and categorize log entries by service characteristics. + +### Step-by-step configuration + +Follow these steps to configure the application log enricher in your application: + +#### 1. Configure Application Metadata + +First, configure the [Application Metadata](application-metadata.md) by calling the methods: + +```csharp +var builder = Host.CreateApplicationBuilder(args); +builder.UseApplicationMetadata() +``` + +This method automatically picks up values from the and saves them to the default configuration section `ambientmetadata:application`. + +Alternatively, you can use this method , which registers a configuration provider for application metadata by picking up the values from the and adds it to the given configuration section name. Then you use method to register the metadata in the dependency injection container, which allow you to pass separately: + +```csharp +var builder = Host.CreateApplicationBuilder(args) + .ConfigureAppConfiguration(static (context, builder) => + builder.AddApplicationMetadata(context.HostingEnvironment)); + +builder.Services.AddApplicationMetadata( + builder.Configuration.GetSection("ambientmetadata:application"))); +``` + +#### 2. Provide additional configuration (optional) + +You can provide additional configuration via `appsettings.json`. There are two properties in the [Application Metadata](application-metadata.md) that don't get values automatically: `BuildVersion` and `DeploymentRing`. If you want to use them, provide values manually: + +:::code language="json" source="snippets/servicelogenricher/appsettings.json" range="2-7"::: + +#### 3. Register the service log enricher + +Register the log enricher into the dependency injection container using : + +```csharp +serviceCollection.AddServiceLogEnricher(); +``` + +You can enable or disable individual options of the enricher using : + +```csharp +serviceCollection.AddServiceLogEnricher(options => +{ + options.BuildVersion = true; + options.DeploymentRing = true; +}); +``` + +Alternatively, configure options using `appsettings.json`: + +:::code language="json" source="snippets/servicelogenricher/appsettings.json" range="8-11"::: + +And apply the configuration using : + +```csharp +var builder = Host.CreateApplicationBuilder(args); +builder.Services.AddServiceLogEnricher(builder.Configuration.GetSection("ApplicationLogEnricherOptions")); + +``` + +### `ApplicationLogEnricherOptions` Configuration options + +The service log enricher supports several configuration options through the class: + +| Property | Default Value | Dimension Name | Description | +|----------|---------------|----------------|-------------| +| `EnvironmentName` | true | `deployment.environment` | Environment name from hosting environment or configuration | +| `ApplicationName` | true | `service.name` | Application name from hosting environment or configuration | +| `BuildVersion` | false | `service.version` | Build version from configuration | +| `DeploymentRing` | false | `DeploymentRing` | Deployment ring from configuration | + +By default, the enricher includes `EnvironmentName` and `ApplicationName` in log entries. The `BuildVersion` and `DeploymentRing` properties are disabled by default and must be explicitly enabled if needed. + +### Complete example + +Here's a complete example showing how to set up the service log enricher: + +**appsettings.json:** + +:::code language="json" source="snippets/servicelogenricher/appsettings.json"::: + +**Program.cs:** + +:::code language="csharp" source="snippets/servicelogenricher/Program.cs" ::: + +### Enriched log output + +With the service log enricher configured, your log output will include service-specific dimensions: + +:::code language="json" source="snippets/servicelogenricher/output-full.json" highlight="8-11" ::: + +## Next steps + +- Learn about [application metadata configuration](application-metadata.md) diff --git a/docs/core/enrichment/application-metadata.md b/docs/core/enrichment/application-metadata.md new file mode 100644 index 0000000000000..08e6dcfad3a3c --- /dev/null +++ b/docs/core/enrichment/application-metadata.md @@ -0,0 +1,239 @@ +--- +title: Application metadata +description: Learn how to use the application metadata to add service-specific information to your service in .NET. +ms.date: 10/14/2025 +--- + +# Application ambient metadata + +The [`Microsoft.Extensions.AmbientMetadata.Application`](https://www.nuget.org/packages/Microsoft.Extensions.AmbientMetadata.Application) NuGet package provides functionality to capture and flow application-level ambient metadata throughout your application. This metadata includes information such as the application name, version, deployment environment, and deployment ring, which is valuable for enriching telemetry, troubleshooting, and analysis. + +## Why use application metadata + +Application metadata provides essential context about your running application that can enhance observability: + +- **Telemetry enrichment**: Automatically add application details to logs, metrics, and traces. +- **Troubleshooting**: Quickly identify which version of your application is experiencing issues. +- **Environment identification**: Distinguish between different environments in your telemetry. +- **Deployment tracking**: Track issues across different deployment rings or regions. +- **Consistent metadata**: Ensure all components in your application use the same metadata values. + +## Install the package + +To get started, install the [📦 Microsoft.Extensions.AmbientMetadata.Application](https://www.nuget.org/packages/Microsoft.Extensions.AmbientMetadata.Application) NuGet package: + +### [.NET CLI](#tab/dotnet-cli) + +```dotnetcli +dotnet add package Microsoft.Extensions.AmbientMetadata.Application +``` + +Or, if you're using .NET 10+ SDK: + +```dotnetcli +dotnet package add Microsoft.Extensions.AmbientMetadata.Application +``` + +### [PackageReference](#tab/package-reference) + +```xml + +``` + +--- + +## Configure application metadata + +Application metadata can be configured through your application's configuration system. The package looks for metadata under the `ambientmetadata:application` configuration section by default. + +### Configure with appsettings.json + +Add the application metadata to your `appsettings.json` file: + +```json +{ + "ambientmetadata": { + "application": { + "ApplicationName": "MyWebApi", + "BuildVersion": "1.0.0", + "DeploymentRing": "Production", + "EnvironmentName": "Production" + } + } +} +``` + +### Configure with IHostBuilder + +Use the extensions method to register application metadata, which populates `ApplicationName` and `EnvironmentName` values automatically from `IHostEnvironment`. +Optionally, you can provide values for `BuildVersion` and `DeploymentRing` via the `appsettings.json` file. + +The following table shows the metadata made available by the provider via : + +| Key | Required? | Where the value comes from| Value Example | Description| +|-|-|-|-|-| +| `ambientmetadata:application:applicationname` | yes | automatically from `IHostEnvironment` |`myApp` | The application name.| +| `ambientmetadata:application:environmentname` | yes | automatically from `IHostEnvironment` | `Production`, `Development`| The environment the application is deployed to.| +| `ambientmetadata:application:buildversion` | no | configure it in `IConfiguration` | `1.0.0-rc1` | The application's build version.| +| `ambientmetadata:application:deploymentring` | no | configure it in `IConfiguration` | `r0`, `public` | The deployment ring from where the application is running.| + +```csharp +var builder = Host.CreateDefaultBuilder(args) + // ApplicationName and EnvironmentName will be imported from `IHostEnvironment` + // BuildVersion and DeploymentRing will be imported from the "appsettings.json" file. +builder.UseApplicationMetadata(); + +var host = builder.Build(); +await host.StartAsync(); + +var metadataOptions = host.Services.GetRequiredService>(); +var buildVersion = metadataOptions.Value.BuildVersion; +``` + +Alternatively, you can achieve the same result as above by doing this: + +```csharp +var builder = Host.CreateApplicationBuilder() + .ConfigureAppConfiguration(static (context, builder) => + builder.AddApplicationMetadata(context.HostingEnvironment)); +builder.Services.AddApplicationMetadata( + builder.Configuration.GetSection("ambientmetadata:application"))); +var host = builder.Build(); + +var metadataOptions = host.Services.GetRequiredService>(); +var buildVersion = metadataOptions.Value.BuildVersion; +``` + +Your `appsettings.json` can have a section as follows : + +:::code language="json" source="snippets/servicelogenricher/appsettings.json" range="2-7"::: + +### Configure with IHostApplicationBuilder + +For applications using : + +```csharp +var builder = Host.CreateApplicationBuilder(args) + // ApplicationName and EnvironmentName will be imported from `IHostEnvironment` + // BuildVersion and DeploymentRing will be imported from the "appsettings.json" file. +builder.UseApplicationMetadata(); + +var host = builder.Build(); +await host.StartAsync(); + +var metadataOptions = host.Services.GetRequiredService>(); +var buildVersion = metadataOptions.Value.BuildVersion; +``` + +Your `appsettings.json` can have a section as follows : + +:::code language="json" source="snippets/servicelogenricher/appsettings.json" range="2-7"::: + +## Access application metadata + +Once configured, you can inject and use the type: + +```csharp +using Microsoft.Extensions.AmbientMetadata; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; + +var builder = Host.CreateApplicationBuilder(args); +builder.UseApplicationMetadata(); + +var host = builder.Build(); + +var metadata = host.Services.GetRequiredService>().Value; +Console.WriteLine($"Application: {metadata.ApplicationName}"); +Console.WriteLine($"Version: {metadata.BuildVersion}"); +Console.WriteLine($"Environment: {metadata.EnvironmentName}"); +Console.WriteLine($"Deployment Ring: {metadata.DeploymentRing}"); +await host.RunAsync(); +``` + +## ApplicationMetadata properties + +The class includes the following properties: + +| Property | Description | +|----------|-------------| +| `ApplicationName` | The name of the application. | +| `BuildVersion` | The version of the application build. | +| `DeploymentRing` | The deployment ring or stage (for example, Canary, Production). | +| `EnvironmentName` | The environment where the application is running (for example, Development, Staging, Production). | + +## Use with logging + +Application metadata is particularly useful for enriching log messages: + +```csharp +using Microsoft.Extensions.AmbientMetadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +var builder = Host.CreateApplicationBuilder(args); + +builder.UseApplicationMetadata(); +builder.Services.AddSingleton(); + +var host = builder.Build(); + +var loggingService = host.Services.GetRequiredService(); +loggingService.LogWithMetadata(); + +await host.RunAsync(); + +public class LoggingService( + ILogger logger, + IOptions metadata) +{ + private readonly ILogger _logger = logger; + private readonly ApplicationMetadata _metadata = metadata.Value; + + public void LogWithMetadata() + { + _logger.LogInformation( + "Processing request in {ApplicationName} v{Version} ({Environment})", + _metadata.ApplicationName, + _metadata.BuildVersion, + _metadata.EnvironmentName); + } +} +``` + +## Custom configuration section + +If you prefer to use a different configuration section name, specify it when calling : + +```csharp +using Microsoft.Extensions.Hosting; + +var builder = Host.CreateApplicationBuilder(args); + +// Use custom configuration section +builder.UseApplicationMetadata("myapp:metadata"); + +var host = builder.Build(); + +await host.RunAsync(); +``` + +With this configuration, your settings would look like: + +```json +{ + "myapp": { + "metadata": { + "ApplicationName": "MyWebApi", // Your ApplicationName will be imported from `IHostEnvironment` + "BuildVersion": "1.0.0", + "DeploymentRing": "Production", + "EnvironmentName": "Production" // Your EnvironmentName will be imported from `IHostEnvironment` + } + } +} +``` diff --git a/docs/core/enrichment/snippets/servicelogenricher/Program.cs b/docs/core/enrichment/snippets/servicelogenricher/Program.cs new file mode 100644 index 0000000000000..9c7b7d03e929b --- /dev/null +++ b/docs/core/enrichment/snippets/servicelogenricher/Program.cs @@ -0,0 +1,23 @@ +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +var builder = Host.CreateApplicationBuilder(args); +builder.UseApplicationMetadata(); +builder.Logging.EnableEnrichment(); +builder.Logging.AddJsonConsole(op => +{ + op.JsonWriterOptions = new JsonWriterOptions + { + Indented = true + }; +}); +builder.Services.AddServiceLogEnricher(builder.Configuration.GetSection("ApplicationLogEnricherOptions")); + +var host = builder.Build(); +var logger = host.Services.GetRequiredService>(); + +logger.LogInformation("This is a sample log message"); + +await host.RunAsync(); diff --git a/docs/core/enrichment/snippets/servicelogenricher/appsettings.json b/docs/core/enrichment/snippets/servicelogenricher/appsettings.json new file mode 100644 index 0000000000000..263f4b20b705c --- /dev/null +++ b/docs/core/enrichment/snippets/servicelogenricher/appsettings.json @@ -0,0 +1,12 @@ +{ + "AmbientMetadata": { + "Application": { + "DeploymentRing": "testring", + "BuildVersion": "1.2.3" + } + }, + "ApplicationLogEnricherOptions": { + "BuildVersion": true, + "DeploymentRing": true + } +} diff --git a/docs/core/enrichment/snippets/servicelogenricher/output-full.json b/docs/core/enrichment/snippets/servicelogenricher/output-full.json new file mode 100644 index 0000000000000..422cb4c0489db --- /dev/null +++ b/docs/core/enrichment/snippets/servicelogenricher/output-full.json @@ -0,0 +1,14 @@ +{ + "EventId": 0, + "LogLevel": "Information", + "Category": "Program", + "Message": "This is a sample log message", + "State": { + "Message": "This is a sample log message", + "service.name": "servicelogenricher", + "deployment.environment": "Production", + "DeploymentRing": "testring", + "service.version": "1.2.3", + "{OriginalFormat}": "This is a sample log message" + } +} \ No newline at end of file diff --git a/docs/core/enrichment/snippets/servicelogenricher/servicelogenricher.csproj b/docs/core/enrichment/snippets/servicelogenricher/servicelogenricher.csproj new file mode 100644 index 0000000000000..714f32824ed44 --- /dev/null +++ b/docs/core/enrichment/snippets/servicelogenricher/servicelogenricher.csproj @@ -0,0 +1,24 @@ + + + + Exe + net9.0 + enable + enable + + + + + + + + + + + + + PreserveNewest + + + + diff --git a/docs/navigate/tools-diagnostics/toc.yml b/docs/navigate/tools-diagnostics/toc.yml index 6074077eebbdf..c9a3ddc0e8082 100644 --- a/docs/navigate/tools-diagnostics/toc.yml +++ b/docs/navigate/tools-diagnostics/toc.yml @@ -450,6 +450,10 @@ items: items: - name: Overview href: ../../core/enrichment/overview.md + - name: Application metadata + href: ../../core/enrichment/application-metadata.md + - name: Application log enricher + href: ../../core/enrichment/application-log-enricher.md - name: Process log enricher href: ../../core/enrichment/process-log-enricher.md - name: Custom enricher