logger_sentry v0.1.1 LoggerBackends behaviour

A simple behaviour module for implementing the backend of Logger.

A LoggerBackends is one backend for Logger and it can handle the event message from the Logger event server. The advantage of using a LoggerBackends implemented using this module is that it will have a standard set of interface functions:

  • get/set the backend log level
  • get the backend log format
  • get/set the backend log metadata

Example

The LoggerBackends behaviour abstracts the common Logger backend. Developers are only required to implement the callbacks and functionality they are interested in.

Let’s start with a code example and then explore the available callbacks. Imagine we want a LoggerBackends that write the log into files:

defmodule Logger.Backends.File do
  use LoggerBackends

  def init(_args) do
    config = Application.get_env(:logger, :file, [])
    {:ok, init(config, %__MODULE__{})}
  end

  def log_event(level, _metadata, output, state) do
    filename = :filename.join(["./logger/", Atom.to_string(level), ".log"])
    :file.write_file(filename, [output], [:append])
    state
  end

  defp init(config, state) do
    level = Keyword.get(config, :level, :info)
    format = Logger.Formatter.compile Keyword.get(config, :format)
    metadata = Keyword.get(config, :metadata, []) |> configure_metadata()
    %{state | format: format, metadata: metadata, level: level}
  end

end

# Set `logger` Application's config
config :logger,
  backends: [:console, Logger.Backends.File],
  sentry: [level: :error,
           format: "$message",
           metadata: []
          ]

# execute Logger.`level` functions
Logger.error("some log message")

We set the Application configure of logger, and add it to backends list, then set log level as needed. So we could execute Logger interface functions as usual, and the file backend will write the log into the files.

There are 2 callbacks required to be implemented in a LoggerBackends. And this behaviour will not define any callbacks for you, you have to define 2 callbacks by yourself.

Link to this section Summary

Callbacks

Initial for Logger backend

Invoked to log the event message as needed

Link to this section Callbacks

Link to this callback init(args)
init(args :: term) :: {:ok, state} when state: any

Initial for Logger backend.

args is the module name which using the LoggerBackends behaviour, as example above in Logger.Backends.File module, the _args in init/1 is Logger.Backends.File.

Returning {:ok, state} will cause the Logger backend to enter its loop and wait for log event message.

Link to this callback log_event(level, metadata, output, state)
log_event(level :: atom, metadata :: list, output :: bitstring, state :: any) :: state when state: any

Invoked to log the event message as needed.

output is the argument after parse of format_event in the LoggerBackends module.

Returning new_state continues the loop with new state new_state.