HangfireIO / HangfireIO/Hangfire
How to implement logging scopes?
Nobody has claimed this yet.
- Dominant language
- C#
- Stars
- 10.1k
- Forks
- 1.8k
- Avg merge
- 1h 19m
- Merged PRs (30d)
- 1
Description
I am using Hangfire to run background jobs. I want to utilize job filters to create logging scopes. However logs created inside the job do not recognize the scope.
The filter will create a logging scope for every job run and augment the log with additional information. The idea is to use AsyncLocal to preserve the reference to the logger across threads.
public class JobLogFilterAttribute : JobFilterAttribute, IServerFilter
{
private readonly AsyncLocal<ILogger> _logger = new();
public JobLogFilterAttribute(IServiceProvider serviceProvider)
{
_logger.Value = serviceProvider.GetService<ILogger<HangfireLogger>>();
}
public void OnPerforming(PerformingContext context)
{
_logger.Value.BeginScope("Foobar");
_logger.Value.LogWarning("Performing");
}
public void OnPerformed(PerformedContext filterContext)
{
_logger.Value.LogWarning("Performed");
_logger.Value = null;
}
}
Logging and the filter are configured like this:
services.AddLogging(conf => conf.AddConsole(options =>
{
options.IncludeScopes = true;
}));
GlobalJobFilters.Filters.Add(new JobLogFilterAttribute(services.BuildServiceProvider()));
Example job:
public class MyJob
{
private readonly ILogger<HangfireLogger> _logger;
public MyJob(ILogger<HangfireLogger> logger)
{
_logger = logger;
}
public async Task Start()
{
_logger.LogInformation("running job");
}
}
The logging inside the filter itself has the correct scope. But the logging inside the job is missing the scope. Any ideas why?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the behavior using the shown JobLogFilterAttribute and MyJob.Start examples. Compare the logging scope observed in OnPerforming and OnPerformed with the log emitted inside Start, then determine whether the missing scope is expected or needs a documented or code-level change.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- backend, observability-sre
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100