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(janitor): add otlp logger for janitor #1686

Merged
merged 2 commits into from
Jan 15, 2025

Conversation

arealmaas
Copy link
Collaborator

@arealmaas arealmaas commented Jan 14, 2025

Description

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)

@arealmaas arealmaas requested a review from a team as a code owner January 14, 2025 15:19
Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

📝 Walkthrough

Walkthrough

This pull request introduces OpenTelemetry integration for the Dialogporten Janitor application. The changes include adding a new OpenTelemetryExtensions class that provides methods for configuring telemetry services, updating the project file with necessary OpenTelemetry-related package references, and modifying the Program.cs to use the new telemetry configuration. The implementation allows for flexible logging and telemetry setup, with the ability to use either OpenTelemetry or console logging based on configuration.

Changes

File Change Summary
src/Digdir.Domain.Dialogporten.Janitor/Common/Extensions/OpenTelemetryExtensions.cs Added new static class with methods for configuring OpenTelemetry tracing, metrics, and logging
src/Digdir.Domain.Dialogporten.Janitor/Digdir.Domain.Dialogporten.Janitor.csproj Added multiple OpenTelemetry-related package references, including Serilog, Azure Monitor, and instrumentation packages
src/Digdir.Domain.Dialogporten.Janitor/Program.cs Updated logging configuration to use OpenTelemetry, added AddDialogportenTelemetry method call

Possibly related PRs

Suggested reviewers

  • knuhau
  • 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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

🧹 Nitpick comments (4)
src/Digdir.Domain.Dialogporten.Janitor/Common/Extensions/OpenTelemetryExtensions.cs (3)

31-36: Refactor duplicated protocol parsing logic

The logic for parsing the OTLP protocol is duplicated in both the AddDialogportenTelemetry method (lines 31-36) and the ParseOtlpProtocol method (lines 137-145). To adhere to the DRY (Don't Repeat Yourself) principle and improve maintainability, consider refactoring the code to use the ParseOtlpProtocol method in AddDialogportenTelemetry.

Apply this diff to refactor the code:

--- a/src/Digdir.Domain.Dialogporten.Janitor/Common/Extensions/OpenTelemetryExtensions.cs
+++ b/src/Digdir.Domain.Dialogporten.Janitor/Common/Extensions/OpenTelemetryExtensions.cs
@@ -31,6 +31,2 @@
-            var otlpProtocol = configuration[OtelExporterOtlpProtocol]?.ToLowerInvariant() switch
-            {
-                "grpc" => OtlpExportProtocol.Grpc,
-                "http/protobuf" => OtlpExportProtocol.HttpProtobuf,
-                _ => throw new ArgumentException($"Unsupported protocol: {configuration[OtelExporterOtlpProtocol]}")
-            };
+            var otlpProtocol = ParseOtlpProtocol(configuration[OtelExporterOtlpProtocol]);

Also applies to: 137-145


28-29: Log a warning when OTLP endpoint is invalid

When the OTLP endpoint is not a well-formed URI, the AddDialogportenTelemetry method exits silently. Consider logging a warning to inform that OpenTelemetry configuration is skipped due to an invalid endpoint. This will aid in diagnosing configuration issues.

Apply this diff to add a log message:

+            if (!Uri.IsWellFormedUriString(configuration[OtelExporterOtlpEndpoint], UriKind.Absolute))
+            {
+                services.AddLogging(loggingBuilder =>
+                {
+                    loggingBuilder.AddConsole();
+                    var logger = loggingBuilder.Services.BuildServiceProvider().GetRequiredService<ILogger<OpenTelemetryExtensions>>();
+                    logger.LogWarning("Invalid OTLP endpoint: {Endpoint}. OpenTelemetry will not be configured.", configuration[OtelExporterOtlpEndpoint]);
+                });
+                return services;
+            }

116-135: Ensure consistent configuration handling in TryWriteToOpenTelemetry

In the TryWriteToOpenTelemetry method, consider handling exceptions more gracefully by logging errors instead of swallowing them silently. This will make debugging easier if there are issues with the OTLP configuration.

Apply this diff to add logging for exceptions:

             try
             {
                 var protocol = ParseOtlpProtocol(otelProtocol);
                 return config.WriteTo.OpenTelemetry(ConfigureOtlpSink(otelEndpoint, protocol));
             }
             catch (ArgumentException ex)
             {
-                return config;
+                Log.Logger.Warning(ex, "Failed to configure OpenTelemetry logging. Falling back to default logger.");
+                return config;
             }
src/Digdir.Domain.Dialogporten.Janitor/Program.cs (1)

16-16: Review necessity of Application Insights telemetry configuration

Even though the application is transitioning from Application Insights to OpenTelemetry, the TelemetryConfiguration.CreateDefault() is still being registered (line 62), and Microsoft.ApplicationInsights.Extensibility is being imported (line 16). If Application Insights is no longer used, consider removing this registration and the associated using directive to clean up unnecessary dependencies.

Apply this diff to remove the unnecessary Application Insights configuration:

-using Microsoft.ApplicationInsights.Extensibility;
 
 // Using two-stage initialization to catch startup errors.
 Log.Logger = new LoggerConfiguration()
     .MinimumLevel.Warning()
@@ -58,7 +57,6 @@ static void BuildAndRun(string[] args)
         .AddInfrastructure(builder.Configuration, builder.Environment)
             .WithoutPubSubCapabilities()
             .Build()
-        .AddSingleton(TelemetryConfiguration.CreateDefault());

Also applies to: 58-62

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8f5ce91 and 11c8065.

📒 Files selected for processing (3)
  • src/Digdir.Domain.Dialogporten.Janitor/Common/Extensions/OpenTelemetryExtensions.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.Janitor/Digdir.Domain.Dialogporten.Janitor.csproj (1 hunks)
  • src/Digdir.Domain.Dialogporten.Janitor/Program.cs (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Dry run deploy apps / Deploy service to test
  • GitHub Check: Dry run deploy apps / Deploy graphql to test
  • GitHub Check: Dry run deploy apps / Deploy web-api-so to test
  • GitHub Check: Dry run deploy apps / Deploy web-api-eu to test
  • GitHub Check: build / build-and-test
🔇 Additional comments (3)
src/Digdir.Domain.Dialogporten.Janitor/Program.cs (2)

Line range hint 8-62: Implementation of OpenTelemetry integration is sound

The updates to the logging configuration and service registrations correctly integrate OpenTelemetry into the application. The use of OpenTelemetryOrConsole and AddDialogportenTelemetry methods provides flexibility and aligns with best practices for telemetry in .NET applications.


19-21: Confirm logging configuration consistency

The logging configurations in both the bootstrap logger (lines 19-21) and the main logger (line 55) use OpenTelemetry sinks. Ensure that this setup does not result in duplicate logs or conflicts between the bootstrap and main logger configurations.

Run the following script to check for duplicate log entries:

Also applies to: 55-55

✅ Verification successful

Bootstrap and main logger configurations are properly implemented

The code ensures no duplicate logging through:

  • Proper disposal of bootstrap logger before main logger initialization
  • Mutually exclusive sink configuration (either Console or OpenTelemetry)
  • Conditional OpenTelemetry setup based on environment configuration
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for duplicate logs when running the application.

# Test: Run the application and inspect the logs for duplicates.
# Expect: No duplicate log entries.

dotnet run --project src/Digdir.Domain.Dialogporten.Janitor/Digdir.Domain.Dialogporten.Janitor.csproj | tee application.log

# Analyze the log file for duplicates
awk '{ print $0 }' application.log | sort | uniq -d

Length of output: 456


Script:

#!/bin/bash
# Find TryWriteToOpenTelemetry implementation
ast-grep --pattern 'TryWriteToOpenTelemetry'

# Find logger configuration patterns
rg -l "LoggerConfiguration" --type cs

# Look for logger disposal or reconfiguration
rg "CloseAndFlush|Log\.Logger" --type cs -A 2

Length of output: 3029


Script:

#!/bin/bash
# Get the OpenTelemetry extension implementation from Janitor project
cat src/Digdir.Domain.Dialogporten.Janitor/Common/Extensions/OpenTelemetryExtensions.cs

# Get the full Program.cs to analyze logger lifecycle
cat src/Digdir.Domain.Dialogporten.Janitor/Program.cs

Length of output: 8374

src/Digdir.Domain.Dialogporten.Janitor/Digdir.Domain.Dialogporten.Janitor.csproj (1)

21-29: New package references enhance telemetry capabilities

The addition of OpenTelemetry and related package references is appropriate and effectively expands the application's logging and telemetry functionality.

@arealmaas arealmaas merged commit 2e1656b into main Jan 15, 2025
23 checks passed
@arealmaas arealmaas deleted the feat/add-otlp-logger-for-janitor branch January 15, 2025 14:57
arealmaas pushed a commit that referenced this pull request Jan 15, 2025
🤖 I have created a release *beep* *boop*
---


##
[1.45.0](v1.44.2...v1.45.0)
(2025-01-15)


### Features

* added id to attachments, ApiActions and GuiActions in DialogCreate
([#1670](#1670))
([470e5a9](470e5a9))
* **apps:** export logs to open telemetry endpoint
([#1617](#1617))
([1a71763](1a71763))
* **janitor:** add otlp logger for janitor
([#1686](#1686))
([2e1656b](2e1656b))


### Bug Fixes

* **app:** Add missing telemetry setup GraphQL and Service
([#1695](#1695))
([601a826](601a826))
* Authentication level claim is 0 in dialog token
([#1654](#1654))
([37e545a](37e545a))
* **graphql:** Add missing activity types
([#1684](#1684))
([a0697ae](a0697ae))
* **graphql:** Set max execution depth to allow inspection query
([#1679](#1679))
([6265110](6265110)),
closes [#1680](#1680)
* **web-api:** re-enable health checks
([#1681](#1681))
([96c2c3e](96c2c3e))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
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