丰富Serlilogs每个篝火工作具有独特的价值

时间:2017-10-16 13:25:47

标签: asp.net-core .net-core hangfire serilog

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

我在Startup.cs

中配置了这样的Serilog
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();

我排队这样的工作:

BackgroundJob.Enqueue<MyService>(myService => myService.DoIt(someParameter));

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

1 个答案:

答案 0 :(得分:0)

对于它的价值,我最终使用服务器/客户端过滤器和GlobalJobFilters注册将其关闭。我遇到的一个令人讨厌的问题是,AutomaticRetryAttribute默认添加到GlobalJobFilters集合,而will log errors for failed jobs类不知道在我们的自定义JobLoggerAttribute中创建的Serilog LogContext 。就个人而言,我知道我只允许手动重试,所以我只是删除了该属性并在IServerFilter.OnPerformed方法中处理了错误。检查我的帖子的结尾,看看如果它适合你,如何删除它。

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

GlobalJobFilters

注册......

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());
    }
}

删除GlobalJobFilters.Filters.Add(new JobLoggerAttribute()); ...

AutomaticRetryAttribute