Successfully added
.NET
by Patrik
Auto-Generate Logging Scopes in .NET Background Services
When building background services in .NET, it’s helpful to include structured logging for better traceability and diagnostics. One common pattern is using logging scopes to include context like the service or task name in each log entry.
Instead of manually providing this context everywhere, you can simplify the process by automatically extracting it based on the class and namespace — making the code cleaner and easier to maintain.
✅ Goal
Replace this verbose pattern:
_logger.BeginScope(LoggingScopeHelper.CreateScope("FeatureName", "WorkerName"));
With a simple, reusable version:
_logger.BeginWorkerScope();
Implementation
🔧 1. Logger Extension
public static class LoggerExtensions
{
public static IDisposable BeginWorkerScope(this ILogger logger)
{
var scopeData = LoggingScopeHelper.CreateScope();
return logger.BeginScope(scopeData);
}
}
🧠 2. Logging Scope Helper
logging
dotnet
diagnostics
background
clean-code
Referenced in:
Comments