0

I have got a series of hangfire jobs and I put in the constructor this piece of code, to use with Serilog/Seq

 public CheckoutExternalToursBookingJob(
      ...omiss...
        ILogger<CheckoutExternalToursBookingJob> logger,
        IEmailSender emailSender)
    {
      ...omiss...
        _logger = logger;
        _emailSender = emailSender;

        _logger.BeginScope(new Dictionary<string, object>
        {
            [CoreConstants.ApplicationName] = CoreConstants.HangFireApplicationName,
            [CoreConstants.HangFireJob] = JobName
        });
    }

Now I use this to have for all the _logger.* logs that information filled.

Since the BeginScope returns an IDisposable should I save it to a local variable, then implement in my jobs the IDisposable interface and do scope.Dispose()?

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
advapi
  • 3,661
  • 4
  • 38
  • 73
  • Normally you want to use a `using` block for the duration of your call to your processing logic - the Disposal removes the properties from the local dictionary, which is not strictly necessary. However the fact that you don't have a call to some inner processing logic suggests that you're not doing it on the actual processing thread, which would be wrong... https://stackoverflow.com/questions/57791868/beginscope-with-serilog https://nblumhardt.com/2016/11/ilogger-beginscope/ https://ayende.com/blog/198690-B/answer-what-does-this-code-print – Ruben Bartelink Jan 10 '23 at 17:32
  • Nono I m calling it inside the ExecuteAsync method I've defined but omissed for simplicity... my question is setting the BeginScope in the constructor allows me to have such properties available till the end of the life of the class? Or do I have to put this inside the execute method? – advapi Jan 11 '23 at 00:35
  • No, the scoped stuff lives in an AsyncLocal/ExecutionContext thing, i.e. is carried with the call chain. So it can't magically live with 'the class' as such. If you are using the Serilog API directly, you can do `var logger = _logger.ForContext("x", value)` and then use that (which chains, hooking in your value(s)). I dont believe MEL provides such an affordance, but I could very easily be wrong. I hope the articles lead you there - I personally have never tried with MEL stuff so please don't consider this advice. – Ruben Bartelink Jan 11 '23 at 09:02

0 Answers0