log4cr

log4cr

A logging library for Crystal, ported from the core of Apache Log4j 2.

Installation

Add the dependency to your shard.yml:

dependencies:
  log4cr:
    github: minor-mn/log4cr

Usage

require "log4cr"

class MyApp::Db
  include Log4cr::Loggable           # provides a `logger` method (named "MyApp::Db")

  def query(sql)
    logger.debug("executing {}", sql)
  rescue ex
    logger.error("query failed: {}", sql, ex)   # a trailing exception is logged with its stack trace
  end
end

log = Log4cr::LogManager.get_logger("main")
log.info("pid={}", Process.pid)
log.debug { expensive_dump }         # the block runs only if DEBUG is enabled
log.warn("retrying", exception: ex)  # the exception can also be passed explicitly
log.debug_enabled?                   # equivalent of isDebugEnabled()

Programmatic configuration

Log4cr.configure do |config|
  config.add_appender Log4cr::ConsoleAppender.new("Console",
    Log4cr::PatternLayout.new("%d{HH:mm:ss.SSS} [%t] %-5level %c{1} - %msg%n"))
  config.add_appender Log4cr::FileAppender.new("File", "logs/app.log",
    Log4cr::PatternLayout.new("%d %-5p %c - %m%n"))
  config.root level: Log4cr::Level::INFO, appenders: ["Console"]
  config.add_logger "MyApp::Db", level: Log4cr::Level::DEBUG, additive: false, appenders: ["File"]
end

Log4cr::Configurator.set_level("MyApp::Db", Log4cr::Level::TRACE)
Log4cr::Configurator.set_root_level(Log4cr::Level::WARN)

YAML configuration

The structure is the same as log4j2.yaml. Keys are case-insensitive.

Configuration:
  Appenders:
    Console:
      name: Console
      target: SYSTEM_OUT
      PatternLayout:
        pattern: "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"
    File:
      name: File
      fileName: logs/app.log
      append: true
      PatternLayout:
        pattern: "%d %p %c - %m%n"
    RollingFile:
      name: Rolling
      fileName: logs/app.log
      filePattern: "logs/app-%d{yyyy-MM-dd}-%i.log.gz"
      PatternLayout:
        pattern: "%d %p %c - %m%n"
      Policies:
        SizeBasedTriggeringPolicy:
          size: 10 MB
      DefaultRolloverStrategy:
        max: 5
  Loggers:
    Root:
      level: info
      AppenderRef:
        ref: Console
    Logger:
      - name: MyApp::Db
        level: debug
        additivity: false
        AppenderRef:
          - ref: File
            level: info

The configuration is looked up in this order:

  1. The file named by the LOG4CR_CONFIGURATION_FILE environment variable
  2. log4cr.yaml or log4cr.yml in the current directory
  3. If neither is found, the default configuration (ERROR level, console output)

To load a file explicitly, use Log4cr::Configurator.configure("path/to/log4cr.yaml").

Size-based rollover

RollingFileAppender moves the file to a name built from filePattern once it grows past the size set by SizeBasedTriggeringPolicy. As in Log4j 2, the size is checked before each write, so a file can exceed the limit by one event.

Log4cr::RollingFileAppender.new("Rolling", "logs/app.log", "logs/app-%i.log.gz",
  Log4cr::PatternLayout.new("%d %-5p %c - %m%n"),
  policy: Log4cr::SizeBasedTriggeringPolicy.new("10 MB"),
  strategy: Log4cr::DefaultRolloverStrategy.new(max: 5))
  • filePattern: %i is the archive index and %d{yyyy-MM-dd} is the time the rolled file was started. A pattern ending in .gz gzips the archive.
  • DefaultRolloverStrategy: max (default 7), min (default 1) and fileIndex
    • max (default): newer archives get higher indexes. When the limit is reached, the oldest is deleted and the rest shift down.
    • min: the newest archive is always min. Older ones shift up, and any past max is deleted.
  • Sizes: 1024, 500KB, 10 MB, 1.5GB (1 KB = 1024 bytes)

JSON Lines (NDJSON)

JsonLayout writes each event as one compact JSON object followed by \n. Field names follow Log4j 2's JsonLayout with compact="true" eventEol="true".

Log4cr::FileAppender.new("Json", "logs/app.ndjson",
  Log4cr::JsonLayout.new(location_info: true, additional_fields: {"service" => "api"}))
{"instant":{"epochSecond":1796317581,"nanoOfSecond":396204000},"thread":"main","level":"ERROR","loggerName":"MyApp::Db","message":"query failed","thrown":{"name":"IO::Error","message":"connection lost","extendedStackTrace":["src/db.cr:15:3 in 'query'"]},"source":{"file":"db.cr","line":17},"service":"api"}
Option (YAML attribute) Default Effect
location_info (locationInfo) false Adds "source": {"file", "line"}
include_stacktrace (includeStacktrace) true false leaves extendedStackTrace out of thrown
stacktrace_as_string (stacktraceAsString) false Writes extendedStackTrace as one string instead of an array of frames
include_time_millis (includeTimeMillis) false Writes "timeMillis" instead of "instant"
timestamp_format (timestampFormat) none Writes "timestamp" formatted with a DateFormat pattern, or "ISO8601" (yyyy-MM-dd'T'HH:mm:ss.SSSXXX)
additional_fields (KeyValuePair) none Extra string fields added to every event

An exception's cause is written as a nested "cause" object inside thrown.

In YAML, use JsonLayout in place of PatternLayout:

File:
  name: Json
  fileName: logs/app.ndjson
  JsonLayout:
    locationInfo: true
    KeyValuePair:
      - key: service
        value: api

Mapping from Log4j 2

Log4j 2 log4cr
LogManager.getLogger(Foo.class) Log4cr::LogManager.get_logger(Foo) / include Log4cr::Loggable
logger.info("a={}", a) logger.info("a={}", a)
logger.isDebugEnabled() logger.debug_enabled?
Level.forName("NOTICE", 350) Log4cr::Level.for_name("NOTICE", 350)
Configurator.setLevel(name, level) Log4cr::Configurator.set_level(name, level)
LogManager.shutdown() Log4cr::LogManager.shutdown (also runs automatically at exit)
Logger hierarchy com.example.Foo Both . and :: act as separators
Thread name %t Fiber name

PatternLayout conversion specifiers

Specifier Output
%d / %date Date and time, e.g. %d{yyyy-MM-dd HH:mm:ss.SSS}, %d{ISO8601}, %d{UNIX_MILLIS}, %d{HH:mm}{Asia/Tokyo}
%p / %level Level
%c / %logger Logger name, e.g. %c{1}, %c{-1}, %c{1.}
%m / %msg / %message Message
%t / %thread Fiber name
%ex / %exception / %throwable Exception ({full}, {short}, {none}, {N}). Appended automatically when the pattern has none.
%F / %file, %L / %line File name and line number of the logging call
%r / %relative Milliseconds since the library was loaded
%n, %% Line separator, %

Format modifiers such as %-5p, %20.30c and %.-10m are supported.

Not implemented (outside the core)

Filters, rollover triggers other than size (such as time-based), AsyncAppender, layouts other than PatternLayout and JsonLayout, Markers, ThreadContext (MDC/NDC), ${...} property substitution, properties-format configuration, and automatic reloading of the configuration.

Development

crystal spec
Repository

log4cr

Owner
Statistic
  • 0
  • 0
  • 0
  • 0
  • 0
  • about 17 hours ago
  • December 3, 2026
License

MIT License

Links
Synced at

Thu, 03 Dec 2026 17:39:13 GMT

Languages