You are given a simple Weather API built in .NET 9.
Your task is to implement structured, configurable, and reliable logging throughout the system.
The API currently exposes two endpoints:
GET /weather/current?city=...→ returns current weather.GET /weather/forecast?city=...→ returns a 5-day forecast.
It uses a fake in-memory service to simulate weather data.
- Use
ILogger(built-in) or integrate a logging library (e.g., Serilog, NLog). - Each log entry should include:
- Timestamp (UTC)
- Log level (Information, Warning, Error, Critical)
- Message
- Correlation/request ID
- Contextual data (e.g., city name for requests)
- Assembly Version
- Environment
- Api name
Information: For successful requests and system events.Warning: For recoverable issues (e.g., incomplete forecast data).Error: For failed operations (e.g., weather service unavailable).Critical: For unhandled exceptions.
- Generate a correlation ID for each request.
- Include the ID in all related log entries.
- Return the correlation ID in the API response headers.
- Log unhandled exceptions.
- Return safe, user-friendly error responses (no internal stack traces).
- Log level should be configurable via
User-Secrets. - Default: Console logging.
- (Optional) Add file logging or JSON output.
-
Set up logging
- Configure logging providers in
Program.cs.
- Configure logging providers in
-
Add request/response logging
- Log incoming requests (method, path, city parameter).
- Log outgoing responses (status code, duration).
-
Add service logging
- Log at
Informationwhen weather is successfully fetched. - Log at
Warningfor partial/missing forecast data. - Log at
Errorwhen the fake service fails. - Log at
Criticalfor unhandled exceptions.
- Log at
-
Add correlation IDs
- Generate one per request.
- Pass through all logs for traceability.
-
File or JSON Logging
- Write logs to a file in JSON format.
-
Request Duration Metrics
- Log duration for each request.
- Trigger a warning if it exceeds a threshold.
-
Centralized Logging
- Integrate with Seq, ELK, or Application Insights.
-
Log Filtering
- Allow filtering by log level or source.
- Proper use of log levels.
- Consistent correlation ID handling.
- No sensitive data in logs.
- Configurable logging (easy to change providers/levels).
- Clean, maintainable, testable code.