Search code examples
loggingcrystal-lang

Global log level in Crystal


I'm writing an application in the Crystal programming language. One of the things I like about Crystal is its extensive standard library, which includes things like a Logger utility.

The logging syntax looks like this:

require "logger"

log = Logger.new(STDOUT)
log.level = Logger::WARN

log.debug("Created logger")
log.info("Program started")
log.warn("Nothing to do!")

(Taken from Crystal documentation)

The problem I'm running into is that it is hard to keep track of severity levels. Either I have to pass the same Logger object to whatever class/method I want logging in, or I have to pass the severity enum.

How should I deal with this issue? Is there an accepted solution in the Crystal community?


Solution

  • You could place the logger on a class, for example

    module MyApp
      class_getter logger = Logger.new.tap { |l| l.level = Logger::WARN }
    end
    

    Then use it with MyApp.logger.info("foo").

    However this has a few drawbacks:

    1. The logging level is global, you can't edit it per-class.
    2. Logging within libraries is impossible (they can't see MyApp)

    Maybe it would be worth opening an issue on the Crystal repo to discuss this.