-
Notifications
You must be signed in to change notification settings - Fork 6k
New .NET diagnostics NuGet packages content. #37455
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
Merged
Changes from all commits
Commits
Show all changes
30 commits
Select commit
Hold shift + click to select a range
3dba013
WIP
IEvangelist 4f68785
Updates to content
IEvangelist 26082bc
Remove inline source
IEvangelist bd1d5f8
Update resource monitoring section
IEvangelist b85bc0b
Fixes
IEvangelist 2d5dbdb
More updates
IEvangelist a2724c8
Add alert
IEvangelist cb3adec
Highlight
IEvangelist 196fa96
Fix output sample
IEvangelist 5274657
Adding some health check bits
IEvangelist 553bd79
Remove extra '>' chars
IEvangelist 2919300
Added health check bits
IEvangelist ca767d5
Fix code example and alert
IEvangelist ab23492
Add to TOC
IEvangelist d3cb7a3
K8s probes
IEvangelist acc0447
Convert alert to note
IEvangelist 018207d
Fix xref links
IEvangelist 01f4340
Added image instead of using source output
IEvangelist 731a442
Added a bit more about k8s
IEvangelist a2a74fc
clean up bits
IEvangelist d75e77b
Some peer feedback addressed
IEvangelist c0f8a01
Added and updated the example
IEvangelist d523189
Split content
IEvangelist 029ceb4
Fix warnings
IEvangelist 44565da
Added and update
IEvangelist 0ee3412
Minor edit pass
IEvangelist 654b3af
Fix code
IEvangelist c5487e0
Address a bit more feedback
IEvangelist 3436954
Address feedback
IEvangelist f6471ba
Added privacy bits
IEvangelist 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| --- | ||
| title: Exception summarization in C# | ||
| description: Learn the value proposition of exception summarization within diagnostic metrics for .NET app development. | ||
| ms.date: 10/30/2023 | ||
| --- | ||
|
|
||
| # Exception summarization | ||
|
|
||
| When you're trying to generate meaningful diagnostic messages for exceptions, maintaining the inclusion of pertinent information can pose a challenge. The standard exception message often lacks critical details that accompany the exception, while invoking the <xref:System.Exception.ToString%2A?displayProperty=nameWithType> method yields an excess of state information. | ||
|
|
||
| This article relies on the [Microsoft.Extensions.Diagnostics.ExceptionSummarization](https://www.nuget.org/packages/Microsoft.Extensions.Diagnostics.ExceptionSummarization) NuGet package. | ||
|
|
||
| ## The goal of exception summarization | ||
|
|
||
| Metric tags typically support a limited number of distinct values, and as such they are not suitable to represent values which are highly variable, such as the result of `Exception.ToString`. An exception summary represents a low-cardinality version of an exception's information, suitable for such cases. | ||
|
|
||
| The goal of exception summarization is twofold: | ||
|
|
||
| - To reduce the cardinality associated with exception state such that exceptions can be reliably counted in metrics. This matters since metric dimensions have limited cardinality. | ||
| - To eliminate privacy-sensitive information from exception state such that some meaningful exception information can be added to logs. | ||
|
|
||
| ## Exception summarization API | ||
|
|
||
| The <xref:Microsoft.Extensions.Diagnostics.ExceptionSummarization.IExceptionSummarizer> interface offers methods for extracting crucial details from recognized exception types, thereby furnishing a singular `string` that serves as the foundation for crafting top-quality diagnostic messages. | ||
|
|
||
| The <xref:Microsoft.Extensions.Diagnostics.ExceptionSummarization.IExceptionSummarizer.Summarize%2A?displayProperty=nameWithType> method systematically traverses the roster of registered summarizers until it identifies a summarizer capable of handling the specific exception type. In the event that no summarizer is capable of recognizing the exception type, a meaningful default exception summary is provided instead. | ||
|
|
||
| The result of the `Summarize` method returns an <xref:Microsoft.Extensions.Diagnostics.ExceptionSummarization.ExceptionSummary> struct, and it contains the following properties: | ||
|
|
||
| - <xref:Microsoft.Extensions.Diagnostics.ExceptionSummarization.ExceptionSummary.Description?displayProperty=nameWithType>: The summary description of the exception. | ||
| - <xref:Microsoft.Extensions.Diagnostics.ExceptionSummarization.ExceptionSummary.AdditionalDetails?displayProperty=nameWithType>: Intended for low-level diagnostic use, this property contains additional details about the exception and has a relatively high cardinality. This property may contain privacy-sensitive information. | ||
| - <xref:Microsoft.Extensions.Diagnostics.ExceptionSummarization.ExceptionSummary.ExceptionType?displayProperty=nameWithType>: The type of the exception, unless inner exceptions are present, in which case both outer and inner types are reflected. | ||
|
|
||
| ## Example exception summarization usage | ||
|
|
||
| The following example demonstrates how to use the `IExceptionSummarizer` interface to retrieve a summary of an exception. | ||
|
|
||
| :::code source="snippets/exception-summary/Program.cs"::: | ||
|
|
||
| The preceding code: | ||
|
|
||
| - Instantiates a new <xref:Microsoft.Extensions.DependencyInjection.ServiceCollection> instance, chaining a call to the <xref:Microsoft.Extensions.Diagnostics.ExceptionSummarization.ExceptionSummarizationExtensions.AddExceptionSummarizer%2A> extension method. | ||
| - The `AddExceptionSummarizer` extension method accepts a delegate that is used to configure the `ExceptionSummarizerBuilder` instance. | ||
| - The `builder` is used to add the HTTP provider, which handles exceptions of type: | ||
| - <xref:System.OperationCanceledException> | ||
| - <xref:System.Threading.Tasks.TaskCanceledException> | ||
| - <xref:System.Net.Sockets.SocketException> | ||
| - <xref:System.Net.WebException> | ||
| - Builds a new `ServiceProvider` instance from the `ServiceCollection` instance. | ||
| - Gets an instance of the `IExceptionSummarizer` interface from the `ServiceProvider` instance. | ||
| - Iterates over a collection of exceptions, calling the `Summarize` method on each exception and displaying the result. | ||
|
|
||
| > [!NOTE] | ||
| > The primary focus in the design of all exception summarization implementations is to provide diagnostic convenience, rather than prioritizing the protection of personally identifiable information (PII). The <xref:Microsoft.Extensions.Diagnostics.ExceptionSummarization.ExceptionSummary.Description?displayProperty=nameWithType> doesn't contain sensitive information, but the <xref:Microsoft.Extensions.Diagnostics.ExceptionSummarization.ExceptionSummary.AdditionalDetails?displayProperty=nameWithType> might contain sensitive information depending on the implementation. |
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,82 @@ | ||
| --- | ||
| title: App health checks in C# | ||
| description: Learn how to use resource utilization and application lifetime health checks in .NET app development. | ||
| ms.date: 10/30/2023 | ||
| --- | ||
|
|
||
| # .NET app health checks in C\# | ||
|
|
||
| In a distributed system, health checks are periodic assessments of the status, availability, and performance of individual nodes or services. These checks ensure that the system functions correctly and efficiently. Health checks are essential for system reliability, and they are typically performed at regular intervals with the results analyzed for decision-making and corrective actions. | ||
|
|
||
| The following heath check status results are possible: | ||
|
|
||
| - <xref:Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Healthy?displayProperty=nameWithType> | ||
| - <xref:Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Degraded?displayProperty=nameWithType> | ||
| - <xref:Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Unhealthy?displayProperty=nameWithType> | ||
|
|
||
| ## Resource utilization health checks | ||
|
|
||
| To perform health checks on the resource utilization of your .NET apps, add a package reference to [Microsoft.Extensions.Diagnostics.HealthChecks.ResourceUtilization](https://www.nuget.org/packages/Microsoft.Extensions.Diagnostics.HealthChecks.ResourceUtilization). On an <xref:Microsoft.Extensions.DependencyInjection.IServiceCollection> instance, chain a call from <xref:Microsoft.Extensions.DependencyInjection.HealthCheckServiceCollectionExtensions.AddHealthChecks%2A> to <xref:Microsoft.Extensions.Diagnostics.HealthChecks.ResourceUtilizationHealthCheckExtensions.AddResourceUtilizationHealthCheck%2A>. The following example demonstrates how to use the `AddResourceUtilizationHealthCheck` extension method to add a resource utilization health check to an `IServiceCollection` instance: | ||
|
|
||
| :::code source="snippets/health-checks/Program.cs"::: | ||
|
|
||
| The preceding code: | ||
|
|
||
| - Creates a new <xref:Microsoft.Extensions.Hosting.HostApplicationBuilder> instance. | ||
| - Adds resource monitoring by calling <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.ResourceMonitoringExtensions.AddResourceMonitoring%2A>. | ||
| - Adds a health check for resource utilization by chaining a call from the <xref:Microsoft.Extensions.DependencyInjection.HealthCheckServiceCollectionExtensions.AddHealthChecks%2A> call to the <xref:Microsoft.Extensions.Diagnostics.HealthChecks.ResourceUtilizationHealthCheckExtensions.AddResourceUtilizationHealthCheck%2A> extension method. | ||
| - Builds the <xref:Microsoft.Extensions.Hosting.IHost> instance as the `app` variable. | ||
| - Gets an instance of the <xref:Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckService> class from the service provider. | ||
| - Performs a health check and displays the result. | ||
| - Runs the application. | ||
|
|
||
| > [!NOTE] | ||
| > The `Microsoft.Extensions.Diagnostics.HealthChecks.ResourceUtilization` library assumes that the consumer will register the dependent call to <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.ResourceMonitoringExtensions.AddResourceMonitoring%2A>. If you don't register this, when resolving the `HealthCheckService` an exception is thrown. | ||
|
|
||
| ## Application lifetime health checks | ||
|
|
||
| To perform health checks on the application lifetime events of <xref:Microsoft.Extensions.Hosting.IHostApplicationLifetime>, use the <xref:Microsoft.Extensions.Diagnostics.HealthChecks.CommonHealthChecksExtensions.AddApplicationLifecycleHealthCheck%2A> extension method available in the [Microsoft.Extensions.Diagnostics.HealthChecks.Common](https://www.nuget.org/packages/Microsoft.Extensions.Diagnostics.HealthChecks.Common) NuGet package. | ||
|
|
||
| This provider will indicate that the application is healthy only when it is fully active. Until the lifetime object indicates the application has started, the provider will report the application as not healthy. When the application starts shutting down, the provider will report the application as unhealthy. | ||
|
|
||
| The library exposes a <xref:Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckService> enabling consumers to request a health check at any time. Consider the following `ExampleService` implementation: | ||
|
|
||
| :::code source="snippets/lifetime-health-checks/ExampleLifecycle.cs"::: | ||
|
|
||
| The preceding code: | ||
|
|
||
| - Defines a new `ExampleLifecycle` class that implements the <xref:Microsoft.Extensions.Hosting.IHostedService> interface. | ||
| - Defines a primary constructor accepting the following parameters: | ||
| - An instance of the <xref:Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckService> class. | ||
| - An instance of the <xref:Microsoft.Extensions.Logging.ILogger%601> class. | ||
| - Implements the <xref:Microsoft.Extensions.Hosting.IHostedLifecycleService> interface, with each method invoking the `CheckHealthAsync` method. | ||
| - Defines a `ReadyAsync` method that invokes the `CheckHealthAsync` method. | ||
| - Defines a custom `CheckHealthAsync` method that captures the caller name and cancellation token, then requests a health check from the `HealthCheckService` instance. The `result` is then logged. | ||
|
|
||
| The only time that the health check service will report a status of <xref:Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Healthy?displayProperty=nameWithType> is after the app has started and before stopping is called. Please consider the following _Program.cs_: | ||
|
|
||
| :::code source="snippets/lifetime-health-checks/Program.cs"::: | ||
|
|
||
| The preceding code: | ||
|
|
||
| - Creates a new <xref:Microsoft.Extensions.Hosting.HostApplicationBuilder> instance assigning to as the `builder` variable. | ||
| - Registers the `ExampleService` as the app's only <xref:Microsoft.Extensions.Hosting.IHostedService>. | ||
| - Adds a health check for the application lifetime events of <xref:Microsoft.Extensions.Hosting.IHostApplicationLifetime> by chaining a call from the <xref:Microsoft.Extensions.DependencyInjection.IHealthChecksBuilder> instance returned by the <xref:Microsoft.Extensions.DependencyInjection.HealthCheckServiceCollectionExtensions.AddHealthChecks%2A> call to the <xref:Microsoft.Extensions.Diagnostics.HealthChecks.CommonHealthChecksExtensions.AddApplicationLifecycleHealthCheck%2A> extension method. | ||
| - The `healthChecksBuilder` instance can be used to add more health checks. | ||
| - Builds the <xref:Microsoft.Extensions.Hosting.IHost> instance as the `app` variable. | ||
| - Gets an `IHostedService` from the service provider, this is the `ExampleService` instance. | ||
| - Calls <xref:System.Threading.Tasks.Task.WhenAll%2A?displayProperty=nameWithType> given two task references: | ||
| - The `DelayAndReportAsync` method, which delays for 500 milliseconds and then invokes the `ReadyAsync` method on the `ExampleService` instance, will evaluate the health check. | ||
| - The <xref:Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(Microsoft.Extensions.Hosting.IHost,System.Threading.CancellationToken)> method, starts the `app`. | ||
|
|
||
| The app outputs logs in the following order, reporting the health check status as it relates to the lifecycle events: | ||
|
|
||
| 1. `StartingAsync`: Unhealthy | ||
| 1. `StartAsync`: Unhealthy | ||
| 1. `StartedAsync`: Unhealthy | ||
| 1. `ReadyAsync`: Healthy | ||
| 1. `StoppingAsync`: Unhealthy | ||
| 1. `StopAsync`: Unhealthy | ||
| 1. `StoppedAsync`: Unhealthy | ||
|
|
||
| In other words, this provider ensures that the application instance only receives traffic when it's ready. If you're developing web apps with ASP.NET Core, there's health checks middleware available. For more information, [Health checks in ASP.NET Core](/aspnet/core/host-and-deploy/health-checks). | ||
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,66 @@ | ||
| --- | ||
| title: Diagnostic resource monitoring | ||
| description: Learn how to use the diagnostic resource monitoring library in .NET. | ||
| ms.date: 10/30/2023 | ||
| --- | ||
|
|
||
| # Resource monitoring | ||
|
|
||
| Resource monitoring involves the continuous measurement of resource utilization over a specified period. The [Microsoft.Extensions.Diagnostics.ResourceMonitoring](https://www.nuget.org/packages/Microsoft.Extensions.Diagnostics.ResourceMonitoring) NuGet package offers a collection of APIs tailored for monitoring the resource utilization of your .NET applications. | ||
|
|
||
| The <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.IResourceMonitor> interface furnishes methods for retrieving real-time information concerning process resource utilization. This interface supports the retrieval of data related to CPU and memory usage and is currently compatible with both Windows and Linux platforms. All resource monitoring diagnostic information is published to OpenTelemetry by default, so there's no need to manually publish this yourself. | ||
|
|
||
| ## Example resource monitoring usage | ||
|
|
||
| The following example demonstrates how to use the `IResourceMonitor` interface to retrieve information about the current process's CPU and memory usage. | ||
|
|
||
| :::code source="snippets/resource-monitoring/Program.cs" id="setup"::: | ||
|
|
||
| The preceding code: | ||
|
|
||
| - Instantiates a new <xref:Microsoft.Extensions.DependencyInjection.ServiceCollection> instance, chaining calls to the <xref:Microsoft.Extensions.DependencyInjection.LoggingServiceCollectionExtensions.AddLogging%2A> and <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.ResourceMonitoringExtensions.AddResourceMonitoring%2A> extension methods. | ||
| - Builds a new <xref:Microsoft.Extensions.DependencyInjection.ServiceProvider> instance from the `ServiceCollection` instance. | ||
| - Gets an instance of the <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.IResourceMonitor> interface from the `ServiceProvider` instance. | ||
|
|
||
| > [!IMPORTANT] | ||
| > The <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring?displayProperty=fullName> package assumes that the consumer will register logging providers with the `Microsoft.Extensions.Logging` package. If you don't register logging, the call to `AddResourceMonitoring` will throw an exception. | ||
|
|
||
| At this point, with the `IResourceMonitor` implementation you'll ask for resource utilization with the <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.IResourceMonitor.GetUtilization%2A?displayProperty=nameWithType> method. The `GetUtilization` method returns a <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.ResourceUtilization> instance that contains the following information: | ||
|
|
||
| - <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.ResourceUtilization.CpuUsedPercentage?displayProperty=nameWithType>: CPU usage as a percentage. | ||
| - <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.ResourceUtilization.MemoryUsedPercentage?displayProperty=nameWithType>: Memory usage as a percentage. | ||
| - <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.ResourceUtilization.MemoryUsedInBytes?displayProperty=nameWithType>: Memory usage in bytes. | ||
| - <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.ResourceUtilization.SystemResources?displayProperty=nameWithType>: System resources. | ||
| - <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.SystemResources.GuaranteedMemoryInBytes?displayProperty=nameWithType>: Guaranteed memory in bytes. | ||
| - <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.SystemResources.MaximumMemoryInBytes?displayProperty=nameWithType>: Maximum memory in bytes. | ||
| - <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.SystemResources.GuaranteedCpuUnits?displayProperty=nameWithType>: Guaranteed CPU in units. | ||
| - <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.SystemResources.MaximumCpuUnits?displayProperty=nameWithType>: Maximum CPU in units. | ||
|
|
||
| ## Extend resource monitoring with Spectre.Console | ||
|
|
||
| Extending this example, you can leverage [Spectre.Console](https://www.nuget.org/packages/Spectre.Console), a well-regarded .NET library designed to simplify the development of visually appealing, cross-platform console applications. With Spectre, you'll be able to present resource utilization data in a tabular format. The following code illustrates the usage of the `IResourceMonitor` interface to access details regarding the CPU and memory usage of the current process, then presenting this data in a table: | ||
|
|
||
| :::code source="snippets/resource-monitoring/Program.cs" id="monitor" highlight="27-28,33-37"::: | ||
|
|
||
| The preceding code: | ||
|
|
||
| - Creates a cancellation token source and a cancellation token. | ||
| - Creates a new `Table` instance, configuring it with a title, caption, and columns. | ||
| - Performs a live render of the `Table` instance, passing in a delegate that will be invoked every three seconds. | ||
| - Gets the current resource utilization information from the `IResourceMonitor` instance and displays it as a new row in the `Table` instance. | ||
|
|
||
| The following is an example of the output from the preceding code: | ||
|
|
||
| :::image type="content" source="media/resource-monitoring-output.png" lightbox="media/resource-monitoring-output.png" alt-text="Example Resource Monitoring app output."::: | ||
|
|
||
| ## Kubernetes probes | ||
|
|
||
| In addition to resource monitoring, apps that exist within a Kubernetes cluster report their health through diagnostic probes. The [Microsoft.Extensions.Diagnostics.Probes](https://www.nuget.org/packages/Microsoft.Extensions.Diagnostics.Probes) NuGet package provides support for Kubernetes probes. It externalizes various [health checks](diagnostic-health-checks.md) that align with various Kubernetes probes, for example: | ||
|
|
||
| - Liveness | ||
| - Readiness | ||
| - Startup | ||
|
|
||
| The library communicates the apps current health to a Kubernetes hosting environment. If a process reports as being unhealthy, Kubernetes doesn't send it any traffic, providing the process time to recover or terminate. | ||
|
|
||
| To add support for Kubernetes probes, add a package reference to [Microsoft.Extensions.Diagnostics.Probes](https://www.nuget.org/packages/Microsoft.Extensions.Diagnostics.Probes). On an <xref:Microsoft.Extensions.DependencyInjection.IServiceCollection> instance, call <xref:Microsoft.Extensions.Diagnostics.Probes.KubernetesProbesExtensions.AddKubernetesProbes%2A>. |
Oops, something went wrong.
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.