Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions docs/core/enrichment/application-log-enricher.md
Original file line number Diff line number Diff line change
@@ -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
<PackageReference Include="Microsoft.Extensions.Telemetry"
Version="*" /> <!-- Adjust version -->
```

---

## 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 <xref:Microsoft.Extensions.Hosting.ApplicationMetadataHostBuilderExtensions.UseApplicationMetadata%2A> methods:

```csharp
var builder = Host.CreateApplicationBuilder(args);
builder.UseApplicationMetadata()
```

This method automatically picks up values from the <xref:Microsoft.Extensions.Hosting.IHostEnvironment> and saves them to the default configuration section `ambientmetadata:application`.

Alternatively, you can use this method <xref:Microsoft.Extensions.Configuration.ApplicationMetadataConfigurationBuilderExtensions.AddApplicationMetadata(Microsoft.Extensions.Configuration.IConfigurationBuilder,Microsoft.Extensions.Hosting.IHostEnvironment,System.String)>, which registers a configuration provider for application metadata by picking up the values from the <xref:Microsoft.Extensions.Hosting.IHostEnvironment> and adds it to the given configuration section name. Then you use <xref:Microsoft.Extensions.DependencyInjection.ApplicationMetadataServiceCollectionExtensions.AddApplicationMetadata(Microsoft.Extensions.DependencyInjection.IServiceCollection,Microsoft.Extensions.Configuration.IConfigurationSection)> method to register the metadata in the dependency injection container, which allow you to pass <xref:Microsoft.Extensions.Configuration.IConfigurationSection> 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 <xref:Microsoft.Extensions.DependencyInjection.ApplicationEnricherServiceCollectionExtensions.AddServiceLogEnricher(Microsoft.Extensions.DependencyInjection.IServiceCollection)>:

```csharp
serviceCollection.AddServiceLogEnricher();
```

You can enable or disable individual options of the enricher using <xref:Microsoft.Extensions.DependencyInjection.ApplicationEnricherServiceCollectionExtensions.AddServiceLogEnricher(Microsoft.Extensions.DependencyInjection.IServiceCollection,System.Action{Microsoft.Extensions.Diagnostics.Enrichment.ApplicationLogEnricherOptions})>:

```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 <xref:Microsoft.Extensions.DependencyInjection.ApplicationEnricherServiceCollectionExtensions.AddServiceLogEnricher(Microsoft.Extensions.DependencyInjection.IServiceCollection,Microsoft.Extensions.Configuration.IConfigurationSection)>:

```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 <xref:Microsoft.Extensions.Diagnostics.Enrichment.ApplicationLogEnricherOptions> 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)
239 changes: 239 additions & 0 deletions docs/core/enrichment/application-metadata.md
Original file line number Diff line number Diff line change
@@ -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
<PackageReference Include="Microsoft.Extensions.AmbientMetadata.Application"
Version="*" /> <!-- Adjust version -->
```

---

## 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 <xref:Microsoft.Extensions.Hosting.ApplicationMetadataHostBuilderExtensions.UseApplicationMetadata%2A> 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 <xref:Microsoft.Extensions.Configuration.IConfiguration>:

| 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<IOptions<ApplicationMetadata>>();
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<IOptions<ApplicationMetadata>>();
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 <xref:Microsoft.Extensions.Hosting.IHostApplicationBuilder>:

```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<IOptions<ApplicationMetadata>>();
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 <xref:Microsoft.Extensions.AmbientMetadata.ApplicationMetadata> 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<IOptions<ApplicationMetadata>>().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 <xref:Microsoft.Extensions.AmbientMetadata.ApplicationMetadata> 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<LoggingService>();

var host = builder.Build();

var loggingService = host.Services.GetRequiredService<LoggingService>();
loggingService.LogWithMetadata();

await host.RunAsync();

public class LoggingService(
ILogger<LoggingService> logger,
IOptions<ApplicationMetadata> metadata)
{
private readonly ILogger<LoggingService> _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 <xref:Microsoft.Extensions.Hosting.ApplicationMetadataHostBuilderExtensions.UseApplicationMetadata``1(``0,System.String)>:

```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`
}
}
}
```
Loading
Loading