Glasgow (glasgow v0.1.0)

View Source

An Elixir logger backend for sending logs to Grafana Loki.

Installation

The package can be installed by adding glasgow to your list of dependencies in mix.exs:

def deps do
[
  {:glasgow, "~> 0.1.0"}
]
end

Configuration

Example of a basic configuration for config.exs or runtime.exs:

config :my_app, :logger, [
{:handler, :glasgow, Glasgow,
 %{
   config: %{
     level: :info,
     url: System.get_env("URL", "http://localhost:3100"),
     labels: [
       {"service_name", "service_1"},
       {"env", "env_1"}
     ]
   },
   formatter: Logger.Formatter.new()
 }}
]

Once defined, the handler can be explicitly attached with add_handlers/1.

For example, in your Application.start/2:

@impl true
def start(_type, _args) do
  ...

  :ok = Logger.add_handlers(:my_app)

  ...

  Supervisor.start_link(children, opts)
end

Advanced Configuration

Elixir Logger handlers can be configured with filters and metadata to provide control and context.

config :my_app, :logger, [
{:handler, :glasgow, Glasgow,
 %{
   config: %{
     level: :info,
     url: System.get_env("URL", "http://localhost:3100"),
     labels: [
       {"service_name", "service_1"},
       {"env", "env_1"}
     ],
     metadata: [:my_metadata_key]
   },
   formatter: Logger.Formatter.new(),
   filters: [filter_name: {&MyModule.filter/2, []}]
 }}
]

Usage

Once the handler has been configured and attached, logs can be sent to Loki using the standard Logger module.

Logger.info("Hello, world!")

The library also provides a send/4 function for sending messages directly and bypass the Logger.

Glasgow.send("http://localhost:3100", [{"label1","value1"}], "message", DateTime.utc_now())

Requirements

The library requires the Rust toolchain because it depends on Snappyrex for Snappy compression.

Summary

Functions

send(base_url, labels, msg, time \\ nil)

@spec send(
  String.t(),
  list(),
  String.t(),
  DateTime.t() | NaiveDateTime.t() | non_neg_integer() | nil
) ::
  :ok | {:error, non_neg_integer(), term()}

Send a single entry to Loki.

Parameters

  • base_url - The base URL of the Loki server.
  • labels - A list of labels to attach to the log entry.
  • msg - The log message.
  • time - The timestamp of the log entry. If not provided, the current time is used.