Automatically add Logger metadata for jobs

Right now I’m doing Logger.metadata(job_id: job_id) at the top of all my jobs. Is there a way I can make this automatic for all jobs? Maybe with middleware or a plugin or something?

As of Oban Pro v1.5, which has an RC coming out tomorrow, there will be a before_process/1 hook you can use for this.

It could look like this:

defmodule MetadataHook do
  def before_process(job) do
    Logger.metadata(job_id: job.id)

    {:ok, job}
  end
end

Oban.Pro.Worker.attach_hook(MetadataHook)
3 Likes

Telemetry events could also work too ya?

3 Likes

They definitely could; I was excited about the new release :slightly_smiling_face:

Note, the advantage of the before_process hook, which doesn’t matter in this context, is that it can modify the job itself before processing.

I had the same problem a few months ago and ended up leveraging telemetry events as well.

I wrote a post with a few examples that may be useful. Adding logger metadata to Oban jobs with telemetry | Cristian Álvarez Belaustegui

3 Likes

Very helpful!

2 Likes