-
Notifications
You must be signed in to change notification settings - Fork 855
Add ASP.NET Core logging example #4821
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
Merged
utpilla
merged 26 commits into
open-telemetry:main
from
reyang:reyang/aspnetcore-logging-example
Sep 15, 2023
Merged
Changes from 24 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
0f06e8f
Add ASP.NET Core logging example
reyang 163b3ab
complete example
reyang 6c08d8d
add more explanation
reyang 3b38af8
reword
reyang f843084
Merge branch 'main' into reyang/aspnetcore-logging-example
reyang ff1b1e2
fix link
reyang 2d0c156
update based on review discussions
reyang 1284dc0
Merge branch 'main' into reyang/aspnetcore-logging-example
reyang 5a469a8
cleanup notes
reyang ee8ef0c
minor fixes
reyang 709fa0e
update output
reyang b907760
Merge branch 'main' into reyang/aspnetcore-logging-example
reyang 0c20b6a
update the docs
reyang 7fd76a8
wording fix
reyang 6d99545
wording fix
reyang dcb62f1
Merge branch 'main' into reyang/aspnetcore-logging-example
reyang f2df0a6
remove default logging providers and simplify the console output
reyang b67ca88
Merge branch 'main' into reyang/aspnetcore-logging-example
reyang 1dcc8f6
Update docs/logs/getting-started-aspnetcore/README.md
reyang 7763463
format
reyang db5648d
reword
reyang 0184cc0
reword
reyang 061748d
clarified that console exporter is not supposed to be used in product…
reyang 96da4af
Merge branch 'main' into reyang/aspnetcore-logging-example
reyang c491e52
Update docs/logs/getting-started-aspnetcore/Program.cs
reyang f95395f
Merge branch 'main' into reyang/aspnetcore-logging-example
utpilla File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| // <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 | ||
| builder.Logging.ClearProviders().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); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
9 changes: 9 additions & 0 deletions
9
docs/logs/getting-started-aspnetcore/appsettings.Development.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| }, | ||
| "AllowedHosts": "*" | ||
| } |
14 changes: 14 additions & 0 deletions
14
docs/logs/getting-started-aspnetcore/getting-started-aspnetcore.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.