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

feat(graphql): configure opentelemetry #1343

Merged
merged 4 commits into from
Oct 24, 2024
Merged

Conversation

arealmaas
Copy link
Collaborator

@arealmaas arealmaas commented Oct 24, 2024

Description

Adds opentelemetry for GraphQL

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

    • Improved error handling during application startup.
    • Enhanced telemetry management for logging.
  • Bug Fixes

    • Refined error logging to filter out specific exceptions.
  • Refactor

    • Streamlined the initialization process for better consistency in telemetry configuration usage.

Copy link
Contributor

coderabbitai bot commented Oct 24, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces significant changes to the Program.cs file in the src/Digdir.Domain.Dialogporten.GraphQL directory. It implements a two-stage initialization process to improve error handling and streamline telemetry configuration management. The TelemetryConfiguration is now instantiated once and reused throughout the application setup, particularly in logging methods. The BuildAndRun method's signature is updated to accept a TelemetryConfiguration parameter, and error handling is refined to filter specific exceptions. Overall, these changes enhance the application's startup process, focusing on logging and telemetry.

Changes

File Path Change Summary
src/Digdir.Domain.Dialogporten.GraphQL/Program.cs - Implemented a two-stage initialization process for error handling.
- Updated BuildAndRun method signature to accept TelemetryConfiguration.
- Modified logger setup to use a single instance of TelemetryConfiguration.
- Introduced builder.ConfigureTelemetry() call.
- Refined error handling for OperationCanceledException.

Possibly related PRs

Suggested reviewers

  • MagnusSandgren

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.

@arealmaas arealmaas marked this pull request as ready for review October 24, 2024 13:14
@arealmaas arealmaas requested a review from a team as a code owner October 24, 2024 13:14
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: 0

🧹 Outside diff range and nitpick comments (2)
src/Digdir.Domain.Dialogporten.GraphQL/Program.cs (2)

Line range hint 44-54: Consider implementing proper disposal of TelemetryConfiguration

While reusing TelemetryConfiguration is efficient, ensure proper cleanup by registering it with the dependency injection container for lifecycle management.

 var builder = WebApplication.CreateBuilder(args);
+builder.Services.AddSingleton(telemetryConfiguration);

Line range hint 21-69: Consider separating ApplicationInsights and OpenTelemetry concerns

The current implementation focuses on ApplicationInsights, but the PR objective is to configure OpenTelemetry. Consider:

  1. Using OpenTelemetry's ApplicationInsights exporter instead of direct ApplicationInsights integration
  2. Implementing separate configuration methods for each telemetry concern
  3. Following the OpenTelemetry SDK setup best practices

Example OpenTelemetry setup:

builder.Services.AddOpenTelemetry()
    .WithTracing(builder => builder
        .AddSource("Dialogporten.GraphQL")
        .SetResourceBuilder(ResourceBuilder.CreateDefault()
            .AddService("Dialogporten.GraphQL"))
        .AddHotChocolateInstrumentation()
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddAzureMonitorTraceExporter());
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between fa3157a and 5dee84b.

📒 Files selected for processing (1)
  • src/Digdir.Domain.Dialogporten.GraphQL/Program.cs (4 hunks)
🔇 Additional comments (3)
src/Digdir.Domain.Dialogporten.GraphQL/Program.cs (3)

Line range hint 30-41: LGTM! Robust exception handling implementation.

The exception handling properly distinguishes between cancellation and unexpected errors, with appropriate logging and cleanup.


21-28: 🛠️ Refactor suggestion

Consider configuring TelemetryConfiguration with application settings

While creating a single TelemetryConfiguration instance is good practice, consider initializing it with application settings instead of using default configuration. This ensures proper instrumentation key and other telemetry settings are applied consistently.

-var telemetryConfiguration = TelemetryConfiguration.CreateDefault();
+var telemetryConfiguration = new TelemetryConfiguration();
+builder.Configuration.GetSection("ApplicationInsights")?.Bind(telemetryConfiguration);

Likely invalid or redundant comment.


68-69: Verify OpenTelemetry configuration implementation

The ConfigureTelemetry extension method is called, but we should verify its implementation to ensure proper setup of OpenTelemetry exporters, samplers, and instrumentation.

✅ Verification successful

Let me try a different search pattern to locate the telemetry configuration implementation.


Let me search for additional OpenTelemetry configuration to get a complete picture.


OpenTelemetry configuration is properly implemented

The ConfigureTelemetry extension method in Digdir.Library.Utils.AspNet has a comprehensive implementation that includes:

  • Service name configuration using the application name
  • Tracing configuration with:
    • Development environment sampling (AlwaysOnSampler)
    • ASP.NET Core instrumentation (excluding health endpoints)
    • HTTP client instrumentation
    • Npgsql (PostgreSQL) instrumentation
  • Metrics configuration with runtime instrumentation
  • Azure Monitor integration when Application Insights connection string is available
  • Fallback to Application Insights SDK for local development
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for ConfigureTelemetry implementation
rg -t cs "ConfigureTelemetry.*{" -A 10

Length of output: 146


Script:

#!/bin/bash
# Search for ConfigureTelemetry implementation with a simpler pattern
rg -t cs "ConfigureTelemetry" -A 10

# Also search for any telemetry-related configuration files
fd -e cs -e json telemetry -i

Length of output: 3057


Script:

#!/bin/bash
# Search for remaining OpenTelemetry configuration
rg -t cs "WithTracing|AddOpenTelemetry" -A 15

# Look for any metrics configuration
rg -t cs "WithMetrics" -A 10

Length of output: 3923

Copy link

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: 0

🧹 Outside diff range and nitpick comments (2)
src/Digdir.Domain.Dialogporten.GraphQL/Program.cs (2)

Line range hint 32-44: Add parameter validation for telemetryConfiguration.

While the error handling and method signature update look good, consider adding parameter validation to ensure the telemetryConfiguration is not null.

 static void BuildAndRun(string[] args, TelemetryConfiguration telemetryConfiguration)
 {
+    ArgumentNullException.ThrowIfNull(telemetryConfiguration);
     var builder = WebApplication.CreateBuilder(args);

Line range hint 21-69: Consider implementing an OpenTelemetry Resource configuration.

To enhance the observability setup, consider adding OpenTelemetry Resource attributes to provide better context for your telemetry data. This would help with service identification and environment classification.

Example implementation:

using OpenTelemetry.Resources;

var resourceBuilder = ResourceBuilder.CreateDefault()
    .AddService(serviceName: "Dialogporten.GraphQL",
                serviceVersion: Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "unknown")
    .AddAttributes(new Dictionary<string, object>
    {
        ["deployment.environment"] = builder.Environment.EnvironmentName,
        ["service.instance.id"] = Environment.MachineName
    });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5dee84b and 489302f.

📒 Files selected for processing (1)
  • src/Digdir.Domain.Dialogporten.GraphQL/Program.cs (4 hunks)
🔇 Additional comments (2)
src/Digdir.Domain.Dialogporten.GraphQL/Program.cs (2)

21-27: Well-implemented two-stage initialization pattern!

The implementation of a bootstrap logger with a shared TelemetryConfiguration instance is a good practice that ensures:

  • Early logging capabilities before the full application starts
  • Efficient resource usage by reusing the telemetry configuration
  • Proper error capture during startup

54-54: 🛠️ Refactor suggestion

Verify OpenTelemetry configuration implementation and consider code organization.

  1. The ConfigureTelemetry() extension method needs verification to ensure proper OpenTelemetry setup.
  2. Consider moving the telemetry configuration closer to other observability-related setup (like Serilog configuration) for better code organization.

Let's verify the telemetry configuration implementation:

Consider reorganizing the builder setup to group related configurations:

     builder.Host.UseSerilog((context, services, configuration) => configuration
         .MinimumLevel.Warning()
         .ReadFrom.Configuration(context.Configuration)
         .ReadFrom.Services(services)
         .Enrich.FromLogContext()
         .WriteTo.Console(formatProvider: CultureInfo.InvariantCulture)
         .WriteTo.ApplicationInsights(telemetryConfiguration, TelemetryConverter.Traces));
 
+    builder.ConfigureTelemetry();
+
     builder.Configuration
         .AddAzureConfiguration(builder.Environment.EnvironmentName)
         .AddLocalConfiguration(builder.Environment);

Also applies to: 68-69

✅ Verification successful

Let me gather more information about the telemetry configuration implementation.


Let me check one more aspect to understand how ApplicationInsights is configured across the application.


Telemetry configuration is properly implemented and well-structured

The verification reveals that:

  1. The ConfigureTelemetry() extension method is well-implemented in AspNetUtilitiesExtensions.cs with:
    • Proper OpenTelemetry service configuration
    • Development-specific sampling
    • ASP.NET Core and HTTP client instrumentation
    • PostgreSQL tracing
  2. ApplicationInsights is correctly integrated with Serilog for logging
  3. The current code organization is actually logical:
    • Bootstrap logging is set up first
    • Application telemetry is configured after basic builder setup
    • This separation is intentional and follows a clear initialization pattern
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for ConfigureTelemetry implementation
rg -l "ConfigureTelemetry.*WebApplicationBuilder" --type cs

# Check for OpenTelemetry setup patterns
ast-grep --pattern 'AddOpenTelemetry()' 

Length of output: 164


Script:

#!/bin/bash
# Check the implementation of ConfigureTelemetry in AspNetUtilitiesExtensions.cs
rg -A 20 "ConfigureTelemetry.*WebApplicationBuilder" src/Digdir.Library.Utils.AspNet/AspNetUtilitiesExtensions.cs

# Look for other telemetry-related configurations
rg -l "OpenTelemetry|ApplicationInsights" --type cs

# Check for any telemetry setup patterns
ast-grep --pattern 'AddTelemetry($$$)'
ast-grep --pattern 'Services.Configure<$_>($$$)'

Length of output: 1573


Script:

#!/bin/bash
# Check ApplicationInsights configuration in GraphQL project
rg -A 10 "ApplicationInsights" src/Digdir.Domain.Dialogporten.GraphQL/Program.cs

# Check if there are any other telemetry configurations in the GraphQL project
rg "ConfigureTelemetry|OpenTelemetry" src/Digdir.Domain.Dialogporten.GraphQL/Program.cs

Length of output: 1343

@arealmaas arealmaas merged commit e31c08b into main Oct 24, 2024
24 checks passed
@arealmaas arealmaas deleted the feat/use-open-telemetry-graphql branch October 24, 2024 14:18
arealmaas added a commit that referenced this pull request Oct 29, 2024
🤖 I have created a release *beep* *boop*
---


##
[1.27.0](v1.26.3...v1.27.0)
(2024-10-29)


### Features

* Add restrictions to Transmissions reference hierarchy
([#1310](#1310))
([e3d53ca](e3d53ca))
* **graphql:** configure opentelemetry
([#1343](#1343))
([e31c08b](e31c08b))
* **infrastructure:** add availability test for apim
([#1327](#1327))
([1f9fa2b](1f9fa2b))
* **service:** configure opentelemetry
([#1342](#1342))
([513d5e4](513d5e4))
* **utils:** configure open telemetry tracing for masstransit in aspnet
package ([#1344](#1344))
([5ec3b84](5ec3b84))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: Are Almaas <[email protected]>
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.

2 participants