Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ASP.NET Core logging example #4821

Merged
merged 26 commits into from
Sep 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
0f06e8f
Add ASP.NET Core logging example
reyang Aug 7, 2023
163b3ab
complete example
reyang Sep 1, 2023
6c08d8d
add more explanation
reyang Sep 1, 2023
3b38af8
reword
reyang Sep 1, 2023
f843084
Merge branch 'main' into reyang/aspnetcore-logging-example
reyang Sep 5, 2023
ff1b1e2
fix link
reyang Sep 5, 2023
2d0c156
update based on review discussions
reyang Sep 6, 2023
1284dc0
Merge branch 'main' into reyang/aspnetcore-logging-example
reyang Sep 6, 2023
5a469a8
cleanup notes
reyang Sep 6, 2023
ee8ef0c
minor fixes
reyang Sep 6, 2023
709fa0e
update output
reyang Sep 6, 2023
b907760
Merge branch 'main' into reyang/aspnetcore-logging-example
reyang Sep 7, 2023
0c20b6a
update the docs
reyang Sep 7, 2023
7fd76a8
wording fix
reyang Sep 7, 2023
6d99545
wording fix
reyang Sep 7, 2023
dcb62f1
Merge branch 'main' into reyang/aspnetcore-logging-example
reyang Sep 8, 2023
f2df0a6
remove default logging providers and simplify the console output
reyang Sep 8, 2023
b67ca88
Merge branch 'main' into reyang/aspnetcore-logging-example
reyang Sep 11, 2023
1dcc8f6
Update docs/logs/getting-started-aspnetcore/README.md
reyang Sep 11, 2023
7763463
format
reyang Sep 11, 2023
db5648d
reword
reyang Sep 11, 2023
0184cc0
reword
reyang Sep 11, 2023
061748d
clarified that console exporter is not supposed to be used in product…
reyang Sep 14, 2023
96da4af
Merge branch 'main' into reyang/aspnetcore-logging-example
reyang Sep 14, 2023
c491e52
Update docs/logs/getting-started-aspnetcore/Program.cs
reyang Sep 15, 2023
f95395f
Merge branch 'main' into reyang/aspnetcore-logging-example
utpilla Sep 15, 2023
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ repo.

If you are new here, please read the getting started docs:

* Logs: [Console](./docs/logs/getting-started-console/README.md)
* Logs: [ASP.NET Core](./docs/logs/getting-started-aspnetcore/README.md) | [Console](./docs/logs/getting-started-console/README.md)
* Metrics: [ASP.NET Core](./docs/metrics/getting-started-aspnetcore/README.md) |
[Console](./docs/metrics/getting-started-console/README.md)
* Traces: [ASP.NET Core](./docs/trace/getting-started-aspnetcore/README.md) |
Expand Down
63 changes: 63 additions & 0 deletions docs/logs/getting-started-aspnetcore/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// <copyright file="Program.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using OpenTelemetry.Logs;
using OpenTelemetry.Resources;

var builder = WebApplication.CreateBuilder(args);

// Remove default providers and add OpenTelemetry logging provider
// For instructional purposes only, disable the default .NET console logging provider to
// use the verbose OpenTelemetry console exporter instead. For most development
// and production scenarios the default console provider works well and there is no need to
// clear these providers.
builder.Logging.ClearProviders();

builder.Logging.AddOpenTelemetry(logging =>
{
logging.IncludeScopes = true;

var resourceBuilder = ResourceBuilder
.CreateDefault()
.AddService(builder.Environment.ApplicationName);

logging.SetResourceBuilder(resourceBuilder)
cijothomas marked this conversation as resolved.
Show resolved Hide resolved
// ConsoleExporter is used for demo purpose only.
// In production environment, ConsoleExporter should be replaced with other exporters (e.g. OTLP Exporter).
.AddConsoleExporter();
cijothomas marked this conversation as resolved.
Show resolved Hide resolved
reyang marked this conversation as resolved.
Show resolved Hide resolved
});

var app = builder.Build();

app.MapGet("/", (ILogger<Program> logger) =>
cijothomas marked this conversation as resolved.
Show resolved Hide resolved
{
logger.FoodPriceChanged("artichoke", 9.99);

return "Hello from OpenTelemetry Logs!";
});

app.Logger.StartingApp();

app.Run();

public static partial class ApplicationLogs
{
[LoggerMessage(EventId = 1, Level = LogLevel.Information, Message = "Starting the app...")]
reyang marked this conversation as resolved.
Show resolved Hide resolved
public static partial void StartingApp(this ILogger logger);

[LoggerMessage(EventId = 2, Level = LogLevel.Information, Message = "Food `{name}` price changed to `{price}`.")]
public static partial void FoodPriceChanged(this ILogger logger, string name, double price);
}
133 changes: 133 additions & 0 deletions docs/logs/getting-started-aspnetcore/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Getting Started with OpenTelemetry .NET Logs in 5 Minutes - ASP.NET Core Application

First, download and install the [.NET
SDK](https://dotnet.microsoft.com/download) on your computer.

Create a new web application:

```sh
dotnet new web -o aspnetcoreapp
cd aspnetcoreapp
```

Install the
[OpenTelemetry.Exporter.Console](../../../src/OpenTelemetry.Exporter.Console/README.md)
and
[OpenTelemetry.Extensions.Hosting](../../../src/OpenTelemetry.Extensions.Hosting/README.md)
packages:

```sh
dotnet add package OpenTelemetry.Exporter.Console
dotnet add package OpenTelemetry.Extensions.Hosting
```

Update the `Program.cs` file with the code from [Program.cs](./Program.cs).

Run the application (using `dotnet run`) and then browse to the URL shown in the
console for your application (e.g. `http://localhost:5000`). You should see the
cijothomas marked this conversation as resolved.
Show resolved Hide resolved
logs output from the console:

```text
cijothomas marked this conversation as resolved.
Show resolved Hide resolved
LogRecord.Timestamp: 2023-09-06T22:59:17.9787564Z
LogRecord.CategoryName: getting-started-aspnetcore
LogRecord.Severity: Info
LogRecord.SeverityText: Information
LogRecord.Body: Starting the app...
LogRecord.Attributes (Key:Value):
cijothomas marked this conversation as resolved.
Show resolved Hide resolved
OriginalFormat (a.k.a Body): Starting the app...
LogRecord.EventId: 1
LogRecord.EventName: StartingApp

...

LogRecord.Timestamp: 2023-09-06T22:59:18.0644378Z
LogRecord.CategoryName: Microsoft.Hosting.Lifetime
LogRecord.Severity: Info
LogRecord.SeverityText: Information
LogRecord.Body: Now listening on: {address}
LogRecord.Attributes (Key:Value):
address: http://localhost:5000
OriginalFormat (a.k.a Body): Now listening on: {address}
LogRecord.EventId: 14
LogRecord.EventName: ListeningOnAddress

...

LogRecord.Timestamp: 2023-09-06T23:00:46.1639248Z
LogRecord.TraceId: 3507087d60ae4b1d2f10e68f4e40784a
LogRecord.SpanId: c51be9f19c598b69
LogRecord.TraceFlags: None
LogRecord.CategoryName: Program
LogRecord.Severity: Info
LogRecord.SeverityText: Information
LogRecord.Body: Food `{name}` price changed to `{price}`.
LogRecord.Attributes (Key:Value):
name: artichoke
price: 9.99
OriginalFormat (a.k.a Body): Food `{name}` price changed to `{price}`.
LogRecord.EventId: 2
LogRecord.EventName: FoodPriceChanged

...
```

Congratulations! You are now collecting logs using OpenTelemetry.

What does the above program do?

The program has cleared the default [logging
providers](https://learn.microsoft.com/dotnet/core/extensions/logging-providers)
then added OpenTelemetry as a logging provider to the ASP.NET Core logging
pipeline. OpenTelemetry SDK is then configured with a
[ConsoleExporter](../../../src/OpenTelemetry.Exporter.Console/README.md) to
export the logs to the console for demonstration purpose (note: ConsoleExporter
is not intended for production usage, other exporters such as [OTLP
Exporter](../../../src/OpenTelemetry.Exporter.OpenTelemetryProtocol/README.md)
should be used instead). In addition, `OpenTelemetryLoggerOptions.IncludeScopes`
is enabled so the logs will include the [log
scopes](https://learn.microsoft.com/dotnet/core/extensions/logging#log-scopes).
From the console output we can see the log scopes that are coming from the
ASP.NET Core framework, and we can see logs from both our logger and the ASP.NET
Core framework loggers, as indicated by the `LogRecord.CategoryName`.

The example has demonstrated the best practice from ASP.NET Core by injecting
generic `ILogger<T>`:

```csharp
app.MapGet("/", (ILogger<Program> logger) =>
{
logger.FoodPriceChanged("artichoke", 9.99);

return "Hello from OpenTelemetry Logs!";
});
```

Following the .NET logging best practice, [compile-time logging source
generation](https://docs.microsoft.com/dotnet/core/extensions/logger-message-generator)
has been used across the example, which delivers high performance, structured
logging, and type-checked parameters:

```csharp
public static partial class ApplicationLogs
{
[LoggerMessage(EventId = 1, Level = LogLevel.Information, Message = "Starting the app...")]
public static partial void StartingApp(this ILogger logger);

[LoggerMessage(EventId = 2, Level = LogLevel.Information, Message = "Food `{name}` price changed to `{price}`.")]
public static partial void FoodPriceChanged(this ILogger logger, string name, double price);
}
```

reyang marked this conversation as resolved.
Show resolved Hide resolved
For logs that occur between `builder.Build()` and `app.Run()` when injecting a
generic `ILogger<T>` is not an option, `app.Logger` is used instead:

```csharp
app.Logger.StartingApp();
```

## Learn more

* [Compile-time logging source
generation](https://docs.microsoft.com/dotnet/core/extensions/logger-message-generator)
* [Customizing the OpenTelemetry .NET SDK](../customizing-the-sdk/README.md)
* [Extending the OpenTelemetry .NET SDK](../extending-the-sdk/README.md)
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"DetailedErrors": true,
cijothomas marked this conversation as resolved.
Show resolved Hide resolved
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions docs/logs/getting-started-aspnetcore/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
utpilla marked this conversation as resolved.
Show resolved Hide resolved
<TargetFrameworks>net6.0;net7.0</TargetFrameworks>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="$(RepoRoot)\src\OpenTelemetry.Exporter.Console\OpenTelemetry.Exporter.Console.csproj" />
<ProjectReference Include="$(RepoRoot)\src\OpenTelemetry.Extensions.Hosting\OpenTelemetry.Extensions.Hosting.csproj" />
</ItemGroup>

</Project>