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

Setup Correspondence with Serilog #652

Merged
merged 2 commits into from
Jan 31, 2025
Merged

Setup Correspondence with Serilog #652

merged 2 commits into from
Jan 31, 2025

Conversation

Ceredron
Copy link
Collaborator

@Ceredron Ceredron commented Jan 30, 2025

Description

Setup Correspondence with Serilog in same way as Broker to make logs structured.

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)
  • All tests run green

Documentation

  • User documentation is updated with a separate linked PR in altinn-studio-docs. (if applicable)

Summary by CodeRabbit

  • Chores
    • Updated project dependencies to improve logging capabilities.
    • Added Serilog packages for enhanced logging and monitoring.
    • Integrated Application Insights for better telemetry tracking.
    • Added console and configuration logging support.
    • Enhanced error handling with logging for application termination events.

Copy link
Contributor

coderabbitai bot commented Jan 30, 2025

📝 Walkthrough

Walkthrough

The pull request introduces Serilog logging capabilities to the Altinn Correspondence API project. It includes the addition of several new package references for Serilog in the project file and the configuration of Serilog in the Program.cs file. The implementation allows for logging to both console and Application Insights, with features for reading configuration settings and enriching logs with contextual information.

Changes

File Change Summary
src/Altinn.Correspondence.API/Altinn.Correspondence.API.csproj Added package references for Serilog:
- Serilog.AspNetCore (v9.0.0)
- Serilog.Extensions.Logging (v9.0.0)
- Serilog.Settings.Configuration (v9.0.0)
- Serilog.Sinks.ApplicationInsights (v4.0.0)
- Serilog.Sinks.Console (v6.0.0)
src/Altinn.Correspondence.API/Program.cs Enhanced logging configuration:
- Added imports for Microsoft.ApplicationInsights and Serilog
- Configured logger with console and Application Insights output
- Wrapped BuildAndRun method in try-catch-finally for error handling

Possibly related PRs

Suggested labels

kind/chore

Suggested reviewers

  • CelineTrammi
  • Andreass2

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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
src/Altinn.Correspondence.API/Program.cs (1)

Line range hint 21-64: Add proper cleanup of Serilog resources.

To ensure proper cleanup of logging resources, wrap the application startup in a try-catch block with Log.CloseAndFlush().

Example implementation:

 static void BuildAndRun(string[] args)
 {
+    Log.Logger = new LoggerConfiguration()
+        .WriteTo.Console()
+        .CreateBootstrapLogger();
+
+    try
+    {
         var builder = WebApplication.CreateBuilder(args);
         builder.Host.UseSerilog((context, services, configuration) => configuration
             .ReadFrom.Configuration(context.Configuration)
             // ... rest of the configuration ...
         );
         
         // ... rest of the setup ...
         
         app.Run();
+    }
+    catch (Exception ex)
+    {
+        Log.Fatal(ex, "Application terminated unexpectedly");
+    }
+    finally
+    {
+        Log.CloseAndFlush();
+    }
 }
🧹 Nitpick comments (1)
src/Altinn.Correspondence.API/Program.cs (1)

24-31: Consider enhancing the Serilog configuration for production readiness.

While the basic setup is good, consider these improvements for a more robust logging infrastructure:

  1. Set minimum log levels for different environments
  2. Add file sink for local logs
  3. Configure log retention policies

Example configuration:

 builder.Host.UseSerilog((context, services, configuration) => configuration
     .ReadFrom.Configuration(context.Configuration)
     .ReadFrom.Services(services)
     .Enrich.FromLogContext()
+    .MinimumLevel.Information()
+    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
     .WriteTo.Console()
+    .WriteTo.File(
+        path: "logs/correspondence-.log",
+        rollingInterval: RollingInterval.Day,
+        retainedFileCountLimit: 7)
     .WriteTo.ApplicationInsights(
         services.GetRequiredService<TelemetryConfiguration>(),
         TelemetryConverter.Traces));
🛑 Comments failed to post (1)
src/Altinn.Correspondence.API/Altinn.Correspondence.API.csproj (1)

21-25: 💡 Codebase verification

Invalid version 4.0.0 specified for Serilog.Sinks.ApplicationInsights

The specified version 4.0.0 does not exist. The latest stable version available is 2.0.20. This needs to be corrected to ensure successful package restoration and builds.

🔗 Analysis chain

Verify compatibility of Serilog.Sinks.ApplicationInsights version.

While most Serilog packages are on version 9.0.0, the ApplicationInsights sink is on 4.0.0. Let's verify if this is the latest compatible version.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check latest versions of Serilog.Sinks.ApplicationInsights and its compatibility

# Get latest version from NuGet
curl -s https://api.nuget.org/v3/registration5-semver1/serilog.sinks.applicationinsights/index.json | jq -r '.items[0].upper'

# Check if there are any known compatibility issues
gh api graphql -f query='
{
  securityVulnerabilities(first: 5, ecosystem: NUGET, package: "Serilog.Sinks.ApplicationInsights") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
      firstPatchedVersion {
        identifier
      }
    }
  }
}'

Length of output: 503


Script:

#!/bin/bash
# Verify package information using nuget.org API
curl -s "https://api.nuget.org/v3/registration5-semver1/serilog.sinks.applicationinsights/page/2.0.20/4.0.0.json"

# Check if package exists in project's lock file
fd -g "*packages.lock.json" --exec cat {}

Length of output: 372


Script:

#!/bin/bash
# Get all versions from NuGet
curl -s "https://api.nuget.org/v3/registration5-semver1/serilog.sinks.applicationinsights/index.json" | jq -r '.items[0].items[].catalogEntry.version'

Length of output: 641

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

🧹 Nitpick comments (1)
src/Altinn.Correspondence.API/Program.cs (1)

19-21: Consider enhancing bootstrap logger configuration.

While the bootstrap logger is correctly configured, it could benefit from minimal error handling capabilities during startup.

Consider enhancing the bootstrap logger:

 Log.Logger = new LoggerConfiguration()
     .WriteTo.Console()
+    .MinimumLevel.Warning()
+    .Enrich.FromLogContext()
     .CreateBootstrapLogger();
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 040804d and e938af6.

📒 Files selected for processing (1)
  • src/Altinn.Correspondence.API/Program.cs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (csharp)
🔇 Additional comments (2)
src/Altinn.Correspondence.API/Program.cs (2)

12-12: LGTM! Required imports added for Serilog integration.

The necessary imports for Serilog and Application Insights have been correctly added.

Also applies to: 16-16


22-33: LGTM! Proper exception handling with logging.

The try-catch-finally block correctly handles application termination:

  • Logs fatal errors during unexpected termination
  • Ensures proper cleanup of logging resources

@mSunberg mSunberg self-requested a review January 31, 2025 10:52
Copy link
Collaborator

@mSunberg mSunberg left a comment

Choose a reason for hiding this comment

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

Well done

@Ceredron Ceredron merged commit fbf255f into main Jan 31, 2025
6 checks passed
@Ceredron Ceredron deleted the feat/correlation-log branch January 31, 2025 11:55
@coderabbitai coderabbitai bot mentioned this pull request Apr 1, 2025
5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants