Elixir Caddy

releaseHex.pmDocumentation

Start Caddy reverse proxy server in Elixir project.

Manage caddy configuration in Elixir.

Add this in deps in mix.exs to install

{:caddy, "~> 2.3.1"}

If caddy bin is set, caddy server will automate start when application start.

Start in extra_applications

def application do
[
extra_applications: [Caddy.Application]
]
end

If caddy_bin is not specifiy, Caddy.Server will not start.

Set Caddy binary when needed.

Set caddy_bin to the path of Caddy binary file and start Caddy.Server.

Caddy.Config.set_bin("/usr/bin/caddy")
Caddy.restart_server()

This will restart server automatically

Caddy.Config.set_bin!("/usr/bin/caddy")

Config

import Config
# dump caddy server log to stdout
config :caddy, dump_log: false
# caddy server will not start, this is useful for testing
config :caddy, start: false
# configure caddy paths
config :caddy, :base_path, "/custom/caddy/path"
config :caddy, :etc_path, "/custom/etc/path"
config :caddy, :run_path, "/custom/run/path"
config :caddy, :tmp_path, "/custom/tmp/path"
config :caddy, :env_file, "/custom/path/envfile"
config :caddy, :pid_file, "/custom/path/caddy.pid"

Telemetry

The library includes comprehensive telemetry support for monitoring Caddy operations. Telemetry events are emitted for:

Logging with Telemetry

All logging operations emit telemetry events. By default, a handler automatically forwards log events to Elixir's Logger:

# Use telemetry-based logging (instead of Logger directly)
Caddy.Telemetry.log_debug("Server starting", module: MyApp)
Caddy.Telemetry.log_info("Configuration loaded", config_id: 123)
Caddy.Telemetry.log_warning("Deprecation warning", function: "old_api")
Caddy.Telemetry.log_error("Failed to connect", reason: :timeout)

Configure logging behavior:

config :caddy,
attach_default_handler: true, # Auto-forward logs to Logger (default: true)
log_level: :info # Minimum level to log (default: :debug)

Custom Telemetry Handlers

Attach custom handlers to process log events:

# Send errors to external monitoring service
:telemetry.attach("error_reporter", [:caddy, :log, :error],
fn _event, _measurements, metadata, _config ->
MyApp.ErrorReporter.report(metadata.message, metadata)
end, %{})
# Monitor log buffer performance
:telemetry.attach("buffer_monitor", [:caddy, :log, :buffered],
fn _event, measurements, _metadata, _config ->
MyApp.Metrics.track_buffer_size(measurements.buffer_size)
end, %{})

Usage Example

# Attach telemetry handler
:telemetry.attach_many("caddy_handler", [
[:caddy, :config, :set],
[:caddy, :server, :start],
[:caddy, :log, :error]
], fn event_name, measurements, metadata, _config ->
IO.inspect({event_name, measurements, metadata})
end, %{})
# Start telemetry poller for system metrics
Caddy.Telemetry.start_poller(30_000)

Available Functions