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 11 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
55 changes: 55 additions & 0 deletions docs/logs/getting-started-aspnetcore/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// <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);

builder.Logging.AddOpenTelemetry(logging =>
{
logging.IncludeScopes = true;
logging.ParseStateValues = true;
reyang marked this conversation as resolved.
Show resolved Hide resolved

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

logging.SetResourceBuilder(resourceBuilder)
cijothomas marked this conversation as resolved.
Show resolved Hide resolved
.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);
}
150 changes: 150 additions & 0 deletions docs/logs/getting-started-aspnetcore/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
# 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 again (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 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

Resource associated with LogRecord:
service.name: getting-started-aspnetcore
service.instance.id: d62727d2-3e80-4780-a984-e85fc861e321
telemetry.sdk.name: opentelemetry
telemetry.sdk.language: dotnet
telemetry.sdk.version: 1.6.0-rc.1.24

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

Resource associated with LogRecord:
service.name: getting-started-aspnetcore
service.instance.id: d62727d2-3e80-4780-a984-e85fc861e321
telemetry.sdk.name: opentelemetry
telemetry.sdk.language: dotnet
telemetry.sdk.version: 1.6.0-rc.1.24

cijothomas marked this conversation as resolved.
Show resolved Hide resolved
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
LogRecord.ScopeValues (Key:Value):
[Scope.0]:SpanId: c51be9f19c598b69
[Scope.0]:TraceId: 3507087d60ae4b1d2f10e68f4e40784a
[Scope.0]:ParentId: 0000000000000000
[Scope.1]:ConnectionId: 0HMTF5KCP0BU9
[Scope.2]:RequestId: 0HMTF5KCP0BU9:00000003
[Scope.2]:RequestPath: /

Resource associated with LogRecord:
service.name: getting-started-aspnetcore
service.instance.id: d62727d2-3e80-4780-a984-e85fc861e321
telemetry.sdk.name: opentelemetry
telemetry.sdk.language: dotnet
telemetry.sdk.version: 1.6.0-rc.1.24
```

Congratulations! You are now collecting logs using OpenTelemetry.

What does the above program do?

The program has added OpenTelemetry as a [logging
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: mention we cleared all existing providers?

provider](https://learn.microsoft.com/dotnet/core/extensions/logging-providers)
to the existing logging pipeline. OpenTelemetry SDK is then configured with a
`ConsoleExporter` to export the logs to the console. 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.
reyang marked this conversation as resolved.
Show resolved Hide resolved

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!";
});
```

To achieve structured logging and high performance, [Compile-time logging source
generation](https://docs.microsoft.com/dotnet/core/extensions/logger-message-generator)
is used:

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