Elixir Logger, log metadata per operation

In the documentation its stated that Each log operation, such as Logger.info/2, allows metadata to be given as argument. but it does not state how to do that.

I’ve tried with Logger.warn(a, [:mfa}]) and Logger.warn(a, [metadata: :mfa}]) and some other random stuff but cannot get it to log the metadata on each operation.

I don’t want to add that metadata for every log my application already has but to add it only to particular log operations, how can it be achieved?

You have to configure a list of metadata keys which should be logged. This is described in docs by a link you’ve sent.

For example, you might wish to include a custom :error_code metadata in your logs:

Logger.error("We have a problem", [error_code: :pc_load_letter])

In your app’s logger configuration, you would need to include the :error_code key and you would need to include $metadata as part of your log format template:

config :logger, :console,
 format: "[$level] $message $metadata\n",
 metadata: [:error_code, :file]

Your logs might then receive lines like this:

[error] We have a problem error_code=pc_load_letter file=lib/app.ex
1 Like

I see, but thats custom metadata, ( which i have working as you suggested) but how do i add the existing mfa metadata per operation?

If I add it to the config file as:

config :logger, :console,
 format: "[$level] $message $metadata\n",
 metadata: [:mfa]

I get it on ALL log operations which is not what i want

If you want more control of the log format you can try custom formatting.