用每个 hangfire 作业的独特价值丰富 Serlilogs

Joe*_*oel 5 serilog hangfire .net-core asp.net-core

我使用 Hangfire 进行后台作业,使用 Serilog 进行日志记录。我正在尝试用 a 来丰富我的 serilogs,TrackingId以便来自特定 Hangfire 作业的所有日志都具有TrackingId我可以过滤的相同内容。

我在以下配置 Serilog Startup.cs

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(Configuration)
    .WriteTo.Seq(serverUrl: serverUrl, apiKey: apiKey)

    // Enrich the logs with a tracking id. Will be a new value per request
    .Enrich.WithProperty("TrackingId", Guid.NewGuid())

    .CreateLogger();
Run Code Online (Sandbox Code Playgroud)

我将这样的工作排入队列:

BackgroundJob.Enqueue<MyService>(myService => myService.DoIt(someParameter));
Run Code Online (Sandbox Code Playgroud)

但是这样做不会为TrackingId每个 Hangfire 作业单独设置。有什么办法可以实现吗?

rya*_*lit 0

无论如何,我最终使用服务器/客户端过滤器和GlobalJobFilters注册来完成此任务,如下所示。我遇到的一个恼人的问题是,AutomaticRetryAttribute默认情况下将添加到GlobalJobFilters集合中,并且该类将记录失败作业的错误,而无需了解在我们的自定义 .xml 文件中创建的 Serilog LogContext JobLoggerAttribute。就我个人而言,我知道我只允许手动重试,因此我只是删除了该属性并处理了方法中的错误IServerFilter.OnPerformed。检查我的帖子的末尾,看看如何删除它(如果这对您有用)。

如果您要允许自动重试,那么您将需要:1) 创建一个自定义属性来装饰并AutomaticRetryAttribute使其了解自定义 LogContext,2) 再次AutomaticRetryAttributeGlobalJobFilters集合中删除默认值,以及 3) 添加您的装饰器属性到收藏。

public class JobLoggerAttribute : JobFilterAttribute, IClientFilter, IServerFilter
{
    private ILogger _log;

    public void OnCreating(CreatingContext filterContext)
    {
        _log = GetLogger();

        _log.Information("Job is being created for {JobType} with arguments {JobArguments}", filterContext.Job.Type.Name, filterContext.Job.Args);
    }

    public void OnCreated(CreatedContext filterContext)
    {
        _log.Information("Job {JobId} has been created.", filterContext.BackgroundJob.Id);
    }

    public void OnPerforming(PerformingContext filterContext)
    {
        if (_log == null)
            _log = GetLogger();

        _log.Information("Job {JobId} is performing.", filterContext.BackgroundJob.Id);
    }

    public void OnPerformed(PerformedContext filterContext)
    {
        _log.Information("Job {JobId} has performed.", filterContext.BackgroundJob.Id);

        if (filterContext.Exception != null)
        {
            _log.Error(
                filterContext.Exception,
                "Job {JobId} failed due to an exception.",
                filterContext.BackgroundJob.Id);
        }

        _log = null;
    }

    private ILogger GetLogger()
    {
        return Log.ForContext(GetType()).ForContext("HangfireRequestId", Guid.NewGuid());
    }
}
Run Code Online (Sandbox Code Playgroud)

还有登记...

GlobalJobFilters.Filters.Add(new JobLoggerAttribute());
Run Code Online (Sandbox Code Playgroud)

删除AutomaticRetryAttribute...

var automaticRetryFilter = GlobalJobFilters.Filters.Where(x => x.Instance is AutomaticRetryAttribute).Single();
GlobalJobFilters.Filters.Remove(automaticRetryFilter.Instance);
Run Code Online (Sandbox Code Playgroud)