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

chore(webapi): Add Opentelemetry tracing and metrics to webapi #1202

Merged
merged 22 commits into from
Oct 21, 2024

Conversation

knuhau
Copy link
Collaborator

@knuhau knuhau commented Sep 30, 2024

Description

Replace Application Insights tracing with Opentelemetry in the webapi

Related Issue(s)

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)

Documentation

  • Documentation is updated (either in docs-directory, Altinnpedia or a separate linked PR in altinn-studio-docs., if applicable)

Summary by CodeRabbit

  • New Features

    • Added new packages for Azure monitoring and OpenTelemetry instrumentation.
    • Improved telemetry and monitoring capabilities with updated application settings.
    • Introduced a new extension method for configuring OpenTelemetry in ASP.NET Core applications.
  • Bug Fixes

    • Minor comment adjustments in SwaggerSnapshotTests for clarity.

Copy link
Contributor

coderabbitai bot commented Sep 30, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

This pull request introduces enhancements to monitoring and instrumentation within the Digdir.Domain.Dialogporten.WebApi project. Key updates include the addition of several new package references for Azure monitoring and OpenTelemetry in the project file. The Program.cs file has been modified to improve telemetry capabilities, including adjustments to the method signature for better configuration handling. An extension method for OpenTelemetry setup has been added, and minor changes were made to the SwaggerSnapshotTests class for comment clarity.

Changes

File Change Summary
src/Digdir.Domain.Dialogporten.WebApi/Digdir.Domain.Dialogporten.WebApi.csproj Added new package references for Azure monitoring and OpenTelemetry instrumentation.
src/Digdir.Domain.Dialogporten.WebApi/Program.cs Modified BuildAndRun method to accept a TelemetryConfiguration parameter and updated telemetry setup for OpenTelemetry.
src/Digdir.Domain.Dialogporten.WebApi/Common/Extensions/WebApplicationBuilderExtensions.cs Added ConfigureTelemetry extension method for setting up OpenTelemetry in ASP.NET Core applications.
tests/Digdir.Domain.Dialogporten.WebApi.Integration.Tests/Features/V1/SwaggerSnapshotTests.cs Minor comment modification in SwaggerSnapshotTests class.

Possibly related PRs

Suggested reviewers

  • MagnusSandgren

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d56888b and ef4c60e.

📒 Files selected for processing (2)
  • src/Digdir.Domain.Dialogporten.WebApi/Common/Extensions/WebApplicationBuilderExtensions.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.WebApi/Digdir.Domain.Dialogporten.WebApi.csproj (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Digdir.Domain.Dialogporten.WebApi/Common/Extensions/WebApplicationBuilderExtensions.cs
🧰 Additional context used
🔇 Additional comments (5)
src/Digdir.Domain.Dialogporten.WebApi/Digdir.Domain.Dialogporten.WebApi.csproj (5)

11-11: LGTM: Azure.Monitor.OpenTelemetry.AspNetCore package addition

The addition of this package aligns with the PR objective of replacing Application Insights with OpenTelemetry. The stable version (1.2.0) addresses previous concerns about using beta versions.


18-18: Confirm the necessity of Npgsql.OpenTelemetry package

The addition of this package (version 8.0.5) supports OpenTelemetry instrumentation for PostgreSQL operations. While it aligns with the overall goal of implementing OpenTelemetry tracing, could you please confirm if PostgreSQL is used in the project and if this instrumentation is necessary?


19-19: LGTM: OpenTelemetry.Instrumentation.Runtime package addition

The addition of this package (version 1.9.0) enhances the OpenTelemetry implementation by providing runtime instrumentation. This will offer valuable insights into application performance, aligning with the PR's objective of improving monitoring capabilities.


21-21: LGTM: OpenTelemetry core package addition

The addition of the core OpenTelemetry package (version 1.9.0) is essential for implementing OpenTelemetry tracing. This directly supports the PR's main objective and ensures consistency with the runtime instrumentation package version.


11-21: Consider cleaning up unused packages

The additions of OpenTelemetry-related packages align well with the PR objectives. However, I noticed that the existing Application Insights package is still present. Consider the following:

  1. If you're fully transitioning to OpenTelemetry, you might want to remove the Microsoft.ApplicationInsights.AspNetCore package.
  2. Review other packages to ensure all are still necessary, as mentioned in a previous comment.

This cleanup will help maintain a lean project file and avoid potential conflicts or confusion in the future.

To help identify unused packages, you can run the following command in the project directory:

This script will help identify potentially unused packages, but please review the results carefully as some packages might be used indirectly.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@knuhau knuhau changed the title Chore(webapi): Add Opentelemetry tracing to webapi [DRAFT] Chore(webapi): Add Opentelemetry tracing to webapi Sep 30, 2024
knuhau added 11 commits October 11, 2024 09:54
# Conflicts:
#	src/Digdir.Domain.Dialogporten.WebApi/Digdir.Domain.Dialogporten.WebApi.csproj
#	src/Digdir.Domain.Dialogporten.WebApi/Program.cs
# Conflicts:
#	src/Digdir.Domain.Dialogporten.WebApi/Digdir.Domain.Dialogporten.WebApi.csproj
# Conflicts:
#	src/Digdir.Domain.Dialogporten.Infrastructure/InfrastructureExtensions.cs
#	src/Digdir.Domain.Dialogporten.WebApi/Digdir.Domain.Dialogporten.WebApi.csproj
#	src/Digdir.Domain.Dialogporten.WebApi/appsettings.Development.json
@knuhau
Copy link
Collaborator Author

knuhau commented Oct 18, 2024

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Oct 18, 2024

✅ Actions performed

Full review triggered.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (3)
src/Digdir.Domain.Dialogporten.Infrastructure/InfrastructureExtensions.cs (1)

99-104: Improved Redis configuration with async support

The changes to the Redis configuration are a step in the right direction. Using ConnectionMultiplexerFactory allows for more flexible and potentially asynchronous connection establishment. However, there's room for further improvement.

Consider modifying the ConnectionMultiplexerFactory to use a truly asynchronous connection method:

 services.AddStackExchangeRedisCache(options =>
-    options.ConnectionMultiplexerFactory = () => Task.FromResult<IConnectionMultiplexer>(
-        ConnectionMultiplexer.Connect(infrastructureSettings.Redis.ConnectionString)
-    ));
+    options.ConnectionMultiplexerFactory = () => ConnectionMultiplexer.ConnectAsync(infrastructureSettings.Redis.ConnectionString));

This change would fully leverage the asynchronous capabilities, potentially improving performance and resource utilization, especially during application startup.

src/Digdir.Domain.Dialogporten.WebApi/Program.cs (2)

Line range hint 60-65: Potential duplication of telemetry data

Using Serilog's Application Insights sink alongside OpenTelemetry's Azure Monitor exporter may send duplicate logs to Application Insights. Consider consolidating logging to use OpenTelemetry exporters exclusively.


139-142: Adjust sampling strategy in development environment

Using AlwaysOnSampler() collects all traces, which can be verbose. Consider using TraceIdRatioBasedSampler with a configurable fraction to control trace volume.

Apply this change to adjust the sampler:

 if (builder.Environment.IsDevelopment())
 {
-    tracing.SetSampler(new AlwaysOnSampler());
+    tracing.SetSampler(new TraceIdRatioBasedSampler(0.5)); // Adjust the fraction as needed
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f213d3d and 95bc9d7.

📒 Files selected for processing (4)
  • src/Digdir.Domain.Dialogporten.Infrastructure/InfrastructureExtensions.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.WebApi/Digdir.Domain.Dialogporten.WebApi.csproj (2 hunks)
  • src/Digdir.Domain.Dialogporten.WebApi/Program.cs (5 hunks)
  • tests/Digdir.Domain.Dialogporten.WebApi.Integration.Tests/Features/V1/SwaggerSnapshotTests.cs (1 hunks)
🧰 Additional context used
🔇 Additional comments (10)
src/Digdir.Domain.Dialogporten.WebApi/Digdir.Domain.Dialogporten.WebApi.csproj (5)

11-11: LGTM: Azure.Monitor.OpenTelemetry.AspNetCore package addition

The addition of this package is appropriate for integrating Azure Monitor with OpenTelemetry in your ASP.NET Core application. It aligns well with the PR objective of transitioning from Application Insights to OpenTelemetry for tracing.


20-24: LGTM: Core OpenTelemetry packages addition

The addition of these core OpenTelemetry packages is excellent and aligns perfectly with the PR objective. Here's a breakdown of their purposes:

  1. OpenTelemetry: Provides the core OpenTelemetry functionality.
  2. OpenTelemetry.Extensions.Hosting: Integrates OpenTelemetry with .NET hosting.
  3. OpenTelemetry.Instrumentation.AspNetCore: Adds instrumentation for ASP.NET Core.
  4. OpenTelemetry.Instrumentation.Http: Provides instrumentation for HTTP clients.
  5. OpenTelemetry.Instrumentation.Runtime: Adds runtime metrics instrumentation.

The consistent version (1.9.0) across all packages ensures compatibility. These additions will significantly enhance your application's telemetry capabilities.


25-25: Caution: Beta package and Redis usage verification

The addition of OpenTelemetry.Instrumentation.StackExchangeRedis is appropriate if your application uses Redis and you want to include Redis operations in your telemetry data. However, there are two points to consider:

  1. This package is currently in beta (version 1.9.0-beta.1). Using beta versions in a production environment may introduce instability. Consider if this risk is acceptable for your use case.

  2. If your application doesn't use Redis, this package may be unnecessary.

Please confirm that the application uses Redis and that you're comfortable with using a beta package. You can verify Redis usage with the following script:

#!/bin/bash
# Search for StackExchange.Redis usage in the codebase
rg --type csharp 'using StackExchange.Redis' -l
rg --type csharp 'IConnectionMultiplexer' -l

If Redis is not used, consider removing this package. If Redis is used but you prefer stability, you might want to wait for a stable release before including this instrumentation.


11-25: Overall assessment: OpenTelemetry integration looks good, with some considerations

The changes to the project file effectively introduce OpenTelemetry integration, aligning well with the PR objective of replacing Application Insights with OpenTelemetry. The additions cover various aspects of telemetry, including core functionality, ASP.NET Core instrumentation, HTTP client instrumentation, and potential database (PostgreSQL) and cache (Redis) integrations.

Considerations and next steps:

  1. Verify the necessity of PostgreSQL and Redis instrumentations based on your application's dependencies.
  2. Assess the risk of using the beta version of the Redis instrumentation package in your environment.
  3. Review and potentially remove or update existing Application Insights related packages that may no longer be needed.
  4. Ensure that the Program.cs and other relevant files are updated to utilize these new packages effectively.
  5. Update the project documentation to reflect the transition from Application Insights to OpenTelemetry.
  6. Plan for comprehensive testing to ensure the new telemetry setup captures all necessary data without performance issues.

To help with the cleanup of potentially obsolete packages, run the following script:

#!/bin/bash
# Search for Application Insights usage in the codebase
rg --type csharp 'using Microsoft.ApplicationInsights' -l

If this search returns no results, consider removing the Microsoft.ApplicationInsights.AspNetCore package from your project file.


19-19: LGTM: Npgsql.OpenTelemetry package addition

The addition of this package is appropriate for integrating OpenTelemetry with Npgsql, which is beneficial if your application uses PostgreSQL. It will allow you to include database operations in your telemetry data.

Please confirm that the application indeed uses PostgreSQL. If not, this package may be unnecessary. You can verify PostgreSQL usage with the following script:

tests/Digdir.Domain.Dialogporten.WebApi.Integration.Tests/Features/V1/SwaggerSnapshotTests.cs (2)

38-38: LGTM: Removed trailing whitespace.

The removal of the trailing space in this comment line is a good practice. It helps maintain clean code and reduces unnecessary differences in version control systems. The comment itself provides valuable context about the alphabetical ordering of properties in the Swagger JSON, which is crucial for maintaining deterministic test results across different platforms.


Line range hint 1-93: Overall code quality is high.

The SwaggerSnapshotTests class is well-structured and thoroughly commented. The test method FailIfSwaggerSnapshotDoesNotMatch effectively ensures that changes to the Swagger JSON are detected and verified. The use of SortJson and SortElement methods to create a deterministic ordering of JSON properties is a clever solution to the cross-platform inconsistency issue.

The code demonstrates good practices such as:

  1. Clear and informative comments
  2. Effective use of snapshot testing
  3. Handling of platform-specific inconsistencies
  4. Proper use of asynchronous programming

No significant issues or areas for improvement are apparent in this file.

src/Digdir.Domain.Dialogporten.WebApi/Program.cs (3)

44-44: Passing TelemetryConfiguration enhances configurability

Passing telemetryConfiguration to the BuildAndRun method improves configurability and decouples the telemetry setup from the method implementation.

Also applies to: 56-56


133-158: OpenTelemetry setup is correctly implemented

The configuration for OpenTelemetry tracing and metrics appears comprehensive, including instrumentation for ASP.NET Core, HTTP clients, PostgreSQL, and Redis. Filtering out health check requests is a good practice to reduce unnecessary data collection.


131-131: Redundant call to AddAuthorization

The call to .AddAuthorization() may be redundant if AddDialogportenAuthentication already adds authorization services. Verify if it's necessary to call both methods.

To confirm, run the following script to search for AddAuthorization calls:

✅ Verification successful

AddAuthorization is not redundant

The AddDialogportenAuthentication method does not call .AddAuthorization(), so the explicit call to .AddAuthorization() is necessary.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all occurrences of AddAuthorization in the codebase.

# Test: Search for AddAuthorization method calls. Expect: Ensure it's not called redundantly.
rg --type cs "\.AddAuthorization\(" -A 2

Length of output: 823


Script:

#!/bin/bash
# Description: Find the definition of AddDialogportenAuthentication and check if it calls AddAuthorization.

# Search for the method definition
rg 'AddDialogportenAuthentication' --type cs -A 10

# Additionally, check if AddAuthorization is called within the AddDialogportenAuthentication method
ast-grep --lang csharp --pattern $'public static IServiceCollection AddDialogportenAuthentication($_) {
  $$$
}' | rg '\.AddAuthorization\('

Length of output: 5181


Script:

#!/bin/bash
# Description: Verify if AddDialogportenAuthentication calls AddAuthorization within its implementation.

# Step 1: Find the files where AddDialogportenAuthentication is defined
FILES=$(rg --type cs 'public\s+static\s+IServiceCollection\s+AddDialogportenAuthentication' --files-with-matches)

# Step 2: For each file, check if AddAuthorization is called within the AddDialogportenAuthentication method
for file in $FILES; do
  echo "Checking in $file"
  # Extract the method body
  METHOD_BODY=$(rg -A 20 'public\s+static\s+IServiceCollection\s+AddDialogportenAuthentication' "$file")
  # Check if AddAuthorization is called within the method body
  echo "$METHOD_BODY" | rg '\.AddAuthorization\('
done

Length of output: 4279

@knuhau knuhau changed the title [DRAFT] Chore(webapi): Add Opentelemetry tracing to webapi Chore(webapi): Add Opentelemetry tracing and metrics to webapi Oct 18, 2024
@knuhau knuhau marked this pull request as ready for review October 18, 2024 10:08
@knuhau knuhau requested a review from a team as a code owner October 18, 2024 10:08
@knuhau knuhau changed the title Chore(webapi): Add Opentelemetry tracing and metrics to webapi chore(webapi): Add Opentelemetry tracing and metrics to webapi Oct 18, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (2)
src/Digdir.Domain.Dialogporten.WebApi/Common/Extensions/WebApplicationBuilderExtensions.cs (2)

20-20: Review Sampler Choice for Development Environment

The AlwaysOnSampler is used in development. While this captures all traces, it may lead to large amounts of data. Consider using AlwaysOffSampler to disable tracing, or TraceIdRatioBasedSampler to sample a percentage of requests.

Would you like assistance in configuring a different sampler for the development environment?


13-36: Consider Externalizing Telemetry Settings

For better flexibility and adherence to the configuration-as-code principle, consider moving telemetry settings to appsettings.json or environment variables. This allows changes without modifying code.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 465d25c and e10b1e3.

📒 Files selected for processing (2)
  • src/Digdir.Domain.Dialogporten.WebApi/Common/Extensions/WebApplicationBuilderExtensions.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.WebApi/Program.cs (6 hunks)
🧰 Additional context used
🔇 Additional comments (7)
src/Digdir.Domain.Dialogporten.WebApi/Common/Extensions/WebApplicationBuilderExtensions.cs (1)

38-46: Verify Application Insights and Azure Monitor Configuration

The code uses UseAzureMonitor() when APPLICATIONINSIGHTS_CONNECTION_STRING is set, and AddApplicationInsightsTelemetry() otherwise. Ensure this logic aligns with your deployment environments and that there are no conflicts between Application Insights SDK and OpenTelemetry.

Run this script to check for other telemetry configurations:

✅ Verification successful

Telemetry Configuration Verified Successfully

The telemetry setup correctly uses UseAzureMonitor() with OpenTelemetry when APPLICATIONINSIGHTS_CONNECTION_STRING is set and falls back to AddApplicationInsightsTelemetry() for local development. No conflicting telemetry configurations were found in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for additional telemetry configurations
# Expected Result: Instances of telemetry configuration without conflicts
rg --type cs 'AddApplicationInsightsTelemetry|UseAzureMonitor' -A 5 -B 5

Length of output: 5238


Script:

#!/bin/bash
# Description: Search for files that configure both OpenTelemetry/AzureMonitor and ApplicationInsightsTelemetry
# Expected Result: List of files with potential conflicting telemetry configurations

rg --type cs '(AddOpenTelemetry|UseAzureMonitor)' | while read -r file; do
  if rg --type cs 'AddApplicationInsightsTelemetry' "$file" > /dev/null; then
    echo "$file"
  fi
done

Length of output: 860


Script:

#!/bin/bash
# Description: Search for files that configure both OpenTelemetry/AzureMonitor and ApplicationInsightsTelemetry
# Expected Result: List of files with potential conflicting telemetry configurations

# Find all .cs files containing AddOpenTelemetry or UseAzureMonitor
telemetry_files=$(rg -l --type cs 'AddOpenTelemetry|UseAzureMonitor')

# Iterate through each file and check for AddApplicationInsightsTelemetry
for file in $telemetry_files; do
  if rg -q 'AddApplicationInsightsTelemetry' "$file"; then
    echo "$file"
  fi
done

Length of output: 513

src/Digdir.Domain.Dialogporten.WebApi/Program.cs (6)

10-10: Namespace inclusion is appropriate

The addition of Digdir.Domain.Dialogporten.WebApi.Common.Extensions is necessary for accessing extension methods like ConfigureTelemetry().


29-34: Previous comment still applies

The suggestion to align the logging configuration with OpenTelemetry remains valid.


39-39: Passing TelemetryConfiguration to BuildAndRun

Passing the TelemetryConfiguration instance to BuildAndRun ensures consistent telemetry configuration throughout the application.


51-51: Method signature updated appropriately

The BuildAndRun method now accepts TelemetryConfiguration, facilitating consistent telemetry setup.


60-60: Using TelemetryConfiguration in Serilog setup

The logger configuration correctly utilizes the passed telemetryConfiguration for Application Insights.


74-74: Configuring telemetry with ConfigureTelemetry()

The call to builder.ConfigureTelemetry(); integrates the OpenTelemetry setup into the application startup process.

arealmaas
arealmaas previously approved these changes Oct 18, 2024
oskogstad
oskogstad previously approved these changes Oct 21, 2024
@knuhau knuhau dismissed stale reviews from oskogstad and arealmaas via ef4c60e October 21, 2024 12:55
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants