Passing Correlation ID in async tasks

Yeah, one way to do it is to set up a Registry as a K/V store. At the time when you save the logger metadata, also run:

Registry.register(MyCorrelationRegistry, make_ref(), [<whatever-metadata-you-want>])

When you launch the task, run the following:

metadata = :"$callers"
|> Process.get([])
|> Enum.find_value(fn parent ->
  case Registry.select(MyCorrelationRegistry, [{{:_, :"$1", :"$2"}, [{:==, :"$1", parent}], [:"$2"]}]) do
    [c] -> c
    _ -> nil
  end
end)
|> List.first

note that if something goes wrong (e.g. tasks not rooted to a process that registered itself) metadata will be nil; also note that this should work for nested Tasks.

2 Likes