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(apps): export logs to open telemetry endpoint #1617

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

arealmaas
Copy link
Collaborator

@arealmaas arealmaas commented Dec 17, 2024

Description

WIP!

Notes:

  • Added loki as a way to view logs in OTLP format locally
  • Confirmed logs are exported
  • Not sure if we need the requestlogging that I tried to replace with a middleware instead of using serilog 🤔
  • todo: figure out if there is any more metadata or enriching we are missing. Should cover most AFAIK.

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)

Copy link
Contributor

coderabbitai bot commented Dec 17, 2024

📝 Walkthrough

Walkthrough

This pull request introduces comprehensive enhancements to observability and local development documentation. The changes focus on integrating Loki for log aggregation, updating OpenTelemetry configurations, and improving local development setup instructions. Key modifications include adding health checks for Jaeger and Loki services, configuring Grafana data sources, and implementing a new request logging middleware. The updates aim to provide clearer guidance on local development, observability, and deployment processes across different platforms.

Changes

File Change Summary
README.md Comprehensive documentation update for local development, observability, and deployment processes
docker-compose-otel.yml Added health checks for Jaeger and Loki services, introduced Loki service, updated Grafana dependencies
local-otel-configuration/grafana-datasources.yml Added Loki data source configuration
local-otel-configuration/loki-config.yaml New configuration file for Loki log aggregation service
local-otel-configuration/otel-collector-config.yaml Updated log exporter to include Loki OTLP exporter
src/Digdir.Domain.Dialogporten.WebApi/Common/Middleware/RequestLoggingMiddleware.cs New middleware for HTTP request logging
src/Digdir.Domain.Dialogporten.WebApi/Program.cs Restructured application startup process
src/Digdir.Library.Utils.AspNet/AspNetUtilitiesExtensions.cs Enhanced telemetry configuration with logging
src/Digdir.Library.Utils.AspNet/Digdir.Library.Utils.AspNet.csproj Added OpenTelemetry Console Exporter package

Possibly related issues

  • Redo export of metrics, traces and logs #1456: Redo export of metrics, traces, and logs
    • The PR's improvements to OpenTelemetry configuration and logging align with the issue's goals of enhancing observability
    • Introduces Loki for log aggregation, which supports the issue's exploration of logging and metrics export

Possibly related PRs

Suggested reviewers

  • Magnus Sandgren
  • Knut Haugen

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.

@arealmaas arealmaas marked this pull request as ready for review December 20, 2024 15:53
@arealmaas arealmaas requested a review from a team as a code owner December 20, 2024 15:53
@arealmaas
Copy link
Collaborator Author

  • Not sure if we need the requestlogging that I tried to replace with a middleware instead of using serilog 🤔
  • todo: figure out if there is any more metadata or enriching we are missing. Should cover most AFAIK.

@MagnusSandgren pretty sure we don't need this anymore, or that there is more data that we need to enrich the logs with 🤔

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

🧹 Nitpick comments (10)
src/Digdir.Domain.Dialogporten.WebApi/Program.cs (1)

191-195: Consider structured logging for unexpected exceptions.

Currently, the application logs to the console for unexpected exceptions. Structured logging (e.g. JSON) can improve troubleshooting and correlation, especially if the logs are streamed to external services.

-catch (Exception ex) when (ex is not OperationCanceledException)
-{
-    Console.WriteLine($"Application terminated unexpectedly: {ex}");
-    throw;
-}
+catch (Exception ex) when (ex is not OperationCanceledException)
+{
+    // Potential alternative approach
+    Log.Logger?.Fatal(ex, "Application terminated unexpectedly.");
+    throw;
+}
local-otel-configuration/grafana-datasources.yml (1)

8-15: Add newline at end of file.

A trailing newline at the end of the file is recommended for better compatibility with various tools and text editors, as highlighted by yamllint.

  maxLines: 1000
+ 
🧰 Tools
🪛 yamllint (1.35.1)

[error] 15-15: no new line character at the end of file

(new-line-at-end-of-file)

src/Digdir.Domain.Dialogporten.WebApi/Common/Middleware/RequestLoggingMiddleware.cs (1)

17-32: Add filtering for health check and metrics endpoints

To reduce noise in logs, consider adding filtering for frequently called monitoring endpoints.

 public async Task InvokeAsync(HttpContext context)
 {
+    // Skip logging for health checks and metrics
+    if (context.Request.Path.StartsWithSegments("/health") ||
+        context.Request.Path.StartsWithSegments("/metrics"))
+    {
+        await _next(context);
+        return;
+    }
     try
     {
         await _next(context);
src/Digdir.Library.Utils.AspNet/Digdir.Library.Utils.AspNet.csproj (1)

14-14: Consider conditionally including the Console exporter

The Console exporter is typically used for development/debugging. Consider moving it to a development-only configuration to reduce overhead in production.

You could:

  1. Move it to a development-only package reference:
<ItemGroup Condition="'$(Configuration)' == 'Debug'">
    <PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.10.0" />
</ItemGroup>
  1. Or configure it conditionally in code using environment variables/configuration settings.
docker-compose-otel.yml (3)

40-54: Add volume persistence for Loki storage

Currently, Loki's data will be lost when the container is removed. Consider adding a named volume for data persistence.

   loki:
     image: grafana/loki:3.2.2
     ports:
       - "3100:3100"
     volumes:
       - ./local-otel-configuration/loki-config.yaml:/etc/loki/local-config.yaml
+      - loki-data:/loki
     command: -config.file=/etc/loki/local-config.yaml

+ volumes:
+   loki-data:

40-54: Add resource limits for Loki

To prevent resource exhaustion, consider adding memory and CPU limits for the Loki service.

   loki:
     image: grafana/loki:3.2.2
+    deploy:
+      resources:
+        limits:
+          memory: 1G
+          cpus: '1'
+        reservations:
+          memory: 256M
+          cpus: '0.5'

67-68: Enhance service dependency configuration

The Grafana dependency on Loki should include a health check condition to ensure Loki is fully ready.

     depends_on:
-      - loki
+      loki:
+        condition: service_healthy
README.md (3)

Line range hint 129-138: Consider adding security considerations for OpenTelemetry configuration.

While the OpenTelemetry configuration is well documented, consider adding a note about securing sensitive information in environment variables, particularly:

  • Connection string handling best practices
  • Endpoint security considerations
  • Resource attribute sanitization

161-226: Consider adding troubleshooting guidance for local development.

The local development setup is well documented, but consider adding:

  • Port conflict resolution steps
  • Common troubleshooting scenarios
  • Health check verification steps
  • Resource requirements and limitations
🧰 Tools
🪛 Markdownlint (0.37.0)

177-177: null
Bare URL used

(MD034, no-bare-urls)


185-185: null
Bare URL used

(MD034, no-bare-urls)


192-192: null
Bare URL used

(MD034, no-bare-urls)


193-193: null
Bare URL used

(MD034, no-bare-urls)


208-208: null
Bare URL used

(MD034, no-bare-urls)


177-177: Format URLs according to markdown best practices.

Convert bare URLs to proper markdown link format for better documentation quality:

-http://localhost:16686
+[http://localhost:16686](http://localhost:16686)

-http://localhost:9090
+[http://localhost:9090](http://localhost:9090)

-http://localhost:3100
+[http://localhost:3100](http://localhost:3100)

-http://localhost:3000
+[http://localhost:3000](http://localhost:3000)

Also applies to: 185-185, 192-192, 193-193, 208-208

🧰 Tools
🪛 Markdownlint (0.37.0)

177-177: null
Bare URL used

(MD034, no-bare-urls)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fb740cd and 77b547a.

📒 Files selected for processing (10)
  • README.md (2 hunks)
  • docker-compose-otel.yml (3 hunks)
  • local-otel-configuration/grafana-datasources.yml (1 hunks)
  • local-otel-configuration/loki-config.yaml (1 hunks)
  • local-otel-configuration/otel-collector-config.yaml (2 hunks)
  • src/Digdir.Domain.Dialogporten.WebApi.Tests/Common/Middleware/RequestLoggingMiddlewareTests.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.WebApi/Common/Middleware/RequestLoggingMiddleware.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.WebApi/Program.cs (3 hunks)
  • src/Digdir.Library.Utils.AspNet/AspNetUtilitiesExtensions.cs (2 hunks)
  • src/Digdir.Library.Utils.AspNet/Digdir.Library.Utils.AspNet.csproj (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/Digdir.Domain.Dialogporten.WebApi.Tests/Common/Middleware/RequestLoggingMiddlewareTests.cs
🧰 Additional context used
🪛 yamllint (1.35.1)
local-otel-configuration/grafana-datasources.yml

[error] 15-15: no new line character at the end of file

(new-line-at-end-of-file)

🪛 Markdownlint (0.37.0)
README.md

177-177: null
Bare URL used

(MD034, no-bare-urls)


185-185: null
Bare URL used

(MD034, no-bare-urls)


192-192: null
Bare URL used

(MD034, no-bare-urls)


193-193: null
Bare URL used

(MD034, no-bare-urls)


208-208: null
Bare URL used

(MD034, no-bare-urls)

🔇 Additional comments (10)
src/Digdir.Library.Utils.AspNet/AspNetUtilitiesExtensions.cs (2)

17-18: LGTM: Required imports for OpenTelemetry logging integration.

The added imports are necessary for implementing OpenTelemetry logging functionality.


162-168: 🛠️ Refactor suggestion

Consider adding additional logging configurations.

While the basic OpenTelemetry logging setup is good, consider adding the following configurations to align with the PR objectives:

  1. Log enrichment for additional metadata
  2. Exception handling configuration, especially for Redis exceptions
  3. Log level configuration
  4. Sampling configuration for production environments

Here's a suggested enhancement:

 if (!builder.Environment.IsDevelopment())
 {
     // Clear existing logging providers. If development, we want to keep the console logging.
     builder.Logging.ClearProviders();
 }

-telemetryBuilder.WithLogging();
+telemetryBuilder.WithLogging(logging =>
+{
+    // Configure log levels
+    logging.SetMinimumLevel(LogLevel.Information);
+    
+    // Add enrichment
+    logging.AddProcessor(new CustomEnrichmentProcessor());
+    
+    // Configure sampling in production
+    if (!builder.Environment.IsDevelopment())
+    {
+        logging.AddSampler(new TraceIdRatioBasedSampler(0.1));
+    }
+    
+    // Configure exception handling
+    logging.AddExceptionProcessor(new CustomExceptionProcessor());
+});

Let's verify if there are any existing logging configurations in the codebase:

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

29-29: Streamlined startup approach looks good.

Switching to the simplified WebApplication builder pattern is a clean approach that reduces complexity in your initialization sequence.


127-127: Confirm alignment with required logging details.

You're using a new custom middleware (.UseRequestLogging()). Ensure it captures all relevant request details, including request headers, correlation IDs, and key telemetry attributes.


27-27: Ensure the middleware dependency is needed.

You added a reference to “Digdir.Domain.Dialogporten.WebApi.Common.Middleware.” Confirm that this namespace is specifically used for the custom request logging to avoid unnecessary using statements.

local-otel-configuration/loki-config.yaml (2)

1-23: Configuration looks comprehensive.

The Loki configuration is well-structured for local testing. Disabling auth (“auth_enabled: false”) might be fine for development, but confirm this remains disabled only in non-production environments.


24-45: Validate retention policies and resource usage.

Your environment sets a 168-hour (7-day) retention. If your log volume is high, consider adjusting storage configs or archiving strategies to avoid excessive disk usage.

Would you like me to script-check if any overrides are present in other config files?

local-otel-configuration/otel-collector-config.yaml (2)

28-29: Loki exporter addition recognized.

Good job adding “otlphttp” to forward logs to Loki. Ensure the endpoint remains consistent across the Docker and local environment.


54-54: Parallel logging exports.

Having both “otlphttp” and “debug” exporters ensures logs are forwarded to Loki while still allowing local debug. Confirm that this duplication aligns with your desired operational flow and doesn't degrade performance.

README.md (1)

Line range hint 129-226: Verify the accuracy of commands and endpoints.

The documentation is comprehensive and well-structured. Let's verify the accuracy of the provided information:

✅ Verification successful

Documentation accurately reflects the OpenTelemetry setup and endpoints

The verification confirms that:

  • All documented ports in the README match exactly with the docker-compose-otel.yml configuration:
    • Grafana (3000)
    • Loki (3100)
    • Prometheus (9090)
    • Jaeger (16686)
    • OTLP receivers (4317/4318)
    • Prometheus metrics (8888/8889)
  • OpenTelemetry configuration variables are correctly referenced in the codebase and match the documented environment variables
  • The docker-compose services (Grafana, Jaeger, Loki, Prometheus) are all present with correct configurations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence and accessibility of documented endpoints and commands

# Check if docker-compose files exist and contain the documented services
echo "Verifying docker-compose configurations..."
rg -l "grafana|jaeger|loki|prometheus" docker-compose*.yml

# Check if the documented ports are consistently referenced
echo "Verifying port configurations..."
rg -A 2 "port.*3000|port.*3100|port.*9090|port.*16686|port.*4317|port.*4318|port.*8888|port.*8889" docker-compose*.yml

# Check if OpenTelemetry configuration is referenced in application code
echo "Verifying OpenTelemetry configuration usage..."
rg -l "OTEL_SERVICE_NAME|OTEL_EXPORTER_OTLP_ENDPOINT|OTEL_EXPORTER_OTLP_PROTOCOL"

Length of output: 936


Script:

#!/bin/bash
# Let's verify the specific port mappings in docker-compose-otel.yml
echo "Checking port mappings in docker-compose-otel.yml..."
cat docker-compose-otel.yml

# Let's also check the actual OpenTelemetry configuration in one of the services
echo -e "\nChecking OpenTelemetry configuration in WebApi Program.cs..."
cat "src/Digdir.Domain.Dialogporten.WebApi/Program.cs"

Length of output: 11227

🧰 Tools
🪛 Markdownlint (0.37.0)

177-177: null
Bare URL used

(MD034, no-bare-urls)


185-185: null
Bare URL used

(MD034, no-bare-urls)


192-192: null
Bare URL used

(MD034, no-bare-urls)


193-193: null
Bare URL used

(MD034, no-bare-urls)


208-208: null
Bare URL used

(MD034, no-bare-urls)

Comment on lines +25 to +30
_logger.LogInformation(
"HTTP {RequestMethod} {RequestPath} responded {StatusCode}",
context.Request.Method,
context.Request.Path,
context.Response.StatusCode);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance log data for better observability

The current logging implementation captures basic request details, but for effective monitoring and debugging in a distributed system, consider including additional telemetry data:

  • Request duration
  • Request/Response sizes
  • User Agent
  • Client IP (with appropriate PII handling)
  • Trace context correlation

Here's a suggested implementation:

 public async Task InvokeAsync(HttpContext context)
 {
+    var sw = Stopwatch.StartNew();
     try
     {
         await _next(context);
     }
     finally
     {
+        sw.Stop();
         _logger.LogInformation(
-            "HTTP {RequestMethod} {RequestPath} responded {StatusCode}",
+            "HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {ElapsedMilliseconds}ms - Size: {RequestLength}/{ResponseLength} - {UserAgent} - {ClientIP} - {TraceId}",
             context.Request.Method,
             context.Request.Path,
-            context.Response.StatusCode);
+            context.Response.StatusCode,
+            sw.ElapsedMilliseconds,
+            context.Request.ContentLength,
+            context.Response.ContentLength,
+            context.Request.Headers.UserAgent,
+            context.Connection.RemoteIpAddress,
+            Activity.Current?.TraceId);
     }
 }

Committable suggestion skipped: line range outside the PR's diff.

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.

1 participant