-
Notifications
You must be signed in to change notification settings - Fork 3
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
base: main
Are you sure you want to change the base?
Conversation
📝 WalkthroughWalkthroughThis 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
Possibly related issues
Possibly related PRs
Suggested reviewers
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
Documentation and Community
|
@MagnusSandgren pretty sure we don't need this anymore, or that there is more data that we need to enrich the logs with 🤔 |
Quality Gate passedIssues Measures |
There was a problem hiding this 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 endpointsTo 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 exporterThe Console exporter is typically used for development/debugging. Consider moving it to a development-only configuration to reduce overhead in production.
You could:
- Move it to a development-only package reference:
<ItemGroup Condition="'$(Configuration)' == 'Debug'"> <PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.10.0" /> </ItemGroup>
- Or configure it conditionally in code using environment variables/configuration settings.
docker-compose-otel.yml (3)
40-54
: Add volume persistence for Loki storageCurrently, 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 LokiTo 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 configurationThe Grafana dependency on Loki should include a health check condition to ensure Loki is fully ready.
depends_on: - - loki + loki: + condition: service_healthyREADME.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
📒 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:
- Log enrichment for additional metadata
- Exception handling configuration, especially for Redis exceptions
- Log level configuration
- 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)
_logger.LogInformation( | ||
"HTTP {RequestMethod} {RequestPath} responded {StatusCode}", | ||
context.Request.Method, | ||
context.Request.Path, | ||
context.Response.StatusCode); | ||
} |
There was a problem hiding this comment.
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.
Description
WIP!
Notes:
Related Issue(s)
Verification
Documentation
docs
-directory, Altinnpedia or a separate linked PR in altinn-studio-docs., if applicable)