Instruction file imported from paonath/PH.DapperUtils.UnitOfWork (
.github/instructions/dotnet.logging.instructions.md). Copyright stays with the author.
Logging Instructions
Logging Practices
When implementing logging in application, adhere to the following guidelines:
Use of Logging Framework
- Utilize the built-in .NET logging framework (
Microsoft.Extensions.Logging). - Ensure that the logging framework is properly configured in the application startup.
- If no provider is configured, use the
NLogpackage.
Log Levels
- Use appropriate log levels (
Trace,Debug,Information,Warning,Error,Critical) based on the importance of the message. - Avoid excessive logging at higher levels (e.g.,
Error,Critical) unless necessary.
Structured Logging
- Implement structured logging by using log message templates and providing structured data (e.g., JSON) as log payloads.
- Leverage the capabilities of the logging framework to enrich log messages with additional context (e.g., user ID, request ID).
Log Message Content
- Ensure log messages are clear, concise, and informative.
- Avoid logging sensitive information (e.g., passwords, personal data).
Exception Logging
- Log exceptions at the
Errorlevel or higher. - Include relevant context (e.g., user ID, request ID) in exception logs.
- Use the
ILoggerinterface to log exceptions with stack traces.
Performance Considerations
- Be mindful of the performance impact of logging, especially in high-throughput scenarios.
- Consider using asynchronous logging to avoid blocking the main application thread.
Operational Practices
- Implement log rotation and retention policies; ensure compliance with data privacy requirements.
- Integrate with monitoring/alerting systems to proactively identify issues.
- Regularly review log configurations and audit log data for security and compliance.
Example Usage
using Microsoft.Extensions.Logging;
public class ExampleService
{
private readonly ILogger<ExampleService> _logger;
public ExampleService(ILogger<ExampleService> logger)
{
_logger = logger;
}
public void PerformOperation(MyClass payload)
{
_logger.LogTrace("{Method} started at {StartTime} - Payload: '{@Payload}'", nameof(PerformOperation), DateTime.UtcNow, payload);
try
{
// Operation logic here
}
catch (Exception ex)
{
_logger.LogError(ex, "{Method} failed with exception: {Error}", nameof(PerformOperation), ex.Message);
throw;
}
_logger.LogTrace("{Method} completed at {EndTime}", nameof(PerformOperation), DateTime.UtcNow);
}
}