Galtzo FLOSS Logo by Aboling0, CC BY-SA 4.0 ruby-lang Logo, Yukihiro Matsumoto, Ruby Visual Identity Team, CC BY-SA 2.5

🪲 DebugLogging

Version GitHub tag (latest SemVer) License: MIT Downloads Rank CodeCov Test Coverage Coveralls Test Coverage QLTY Test Coverage QLTY Maintainability CI Heads CI Runtime Dependencies @ HEAD CI Current CI Truffle Ruby CI JRuby Deps Locked Deps Unlocked CI Test Coverage CI Style CodeQL Apache SkyWalking Eyes License Compatibility Check

if ci_badges.map(&:color).detect { it != "green"} ☝️ let me know, as I may have missed the discord notification.


if ci_badges.map(&:color).all? { it == "green"} 👇️ send money so I can do more of this. FLOSS maintenance is now my full-time job.

OpenCollective Backers OpenCollective Sponsors Sponsor Me on Github Liberapay Goal Progress Donate on PayPal Buy me a coffee Donate on Polar Donate at ko-fi.com

👣 How will this project approach the September 2025 hostile takeover of RubyGems? 🚑️ I've summarized my thoughts in [this blog post](https://dev.to/galtzo/hostile-takeover-of-rubygems-my-thoughts-5hlo).

🌻 Synopsis

💡 Info you can shake a stick at

Tokens to Remember Gem name Gem namespace
Works with JRuby JRuby 9.4 Compat JRuby current Compat JRuby HEAD Compat
Works with Truffle Ruby Truffle Ruby 23.1 Compat
Truffle Ruby 24.2 Compat Truffle Ruby 25.0 Compat Truffle Ruby current Compat
Works with MRI Ruby 4 Ruby 4.0 Compat Ruby current Compat Ruby HEAD Compat
Works with MRI Ruby 3 Ruby 3.1 Compat Ruby 3.2 Compat Ruby 3.3 Compat Ruby 3.4 Compat
Support & Community Join Me on Daily.dev's RubyFriends Live Chat on Discord Get help from me on Upwork Get help from me on Codementor
Source Source on GitLab.com Source on CodeBerg.org Source on Github.com The best SHA: dQw4w9WgXcQ!
Documentation Current release on RubyDoc.info YARD on Galtzo.com Maintainer Blog GitLab Wiki GitHub Wiki
Compliance License: MIT Apache license compatibility: Category A 📄ilo-declaration-img Security Policy Contributor Covenant 2.1 SemVer 2.0.0
Style Enforced Code Style Linter Keep-A-Changelog 1.0.0 Gitmoji Commits Compatibility appraised by: appraisal2
Maintainer 🎖️ Follow Me on LinkedIn Follow Me on Ruby.Social Follow Me on Bluesky Contact Maintainer My technical writing
... 💖 Find Me on WellFound: Find Me on CrunchBase My LinkTree More About Me 🧊 🐙 🛖 🧪

Compatibility

Compatible with MRI Ruby 3.1+, and concordant releases of JRuby, and TruffleRuby. CI workflows and Appraisals are generated for MRI Ruby 3.1+. This test floor is configured by ruby.test_minimum in .kettle-jem.yml and may be higher than the gem's runtime compatibility floor when legacy Rubies are not practical for the current toolchain.

🚚 Amazing test matrix was brought to you by 🔎 appraisal2 🔎 and the color 💚 green 💚
👟 Check it out! github.com/appraisal-rb/appraisal2

Federated DVCS

Find this repo on federated forges (Coming soon!) | Federated [DVCS][💎d-in-dvcs] Repository | Status | Issues | PRs | Wiki | CI | Discussions | |-------------------------------------------------|-----------------------------------------------------------------------|---------------------------|--------------------------|---------------------------|--------------------------|------------------------------| | 🧪 [galtzo-floss/debug_logging on GitLab][📜src-gl] | The Truth | [💚][🤝gl-issues] | [💚][🤝gl-pulls] | [💚][📜gl-wiki] | 🐭 Tiny Matrix | ➖ | | 🧊 [galtzo-floss/debug_logging on CodeBerg][📜src-cb] | An Ethical Mirror ([Donate][🤝cb-donate]) | [💚][🤝cb-issues] | [💚][🤝cb-pulls] | ➖ | ⭕️ No Matrix | ➖ | | 🐙 [galtzo-floss/debug_logging on GitHub][📜src-gh] | Another Mirror | [💚][🤝gh-issues] | [💚][🤝gh-pulls] | [💚][📜gh-wiki] | 💯 Full Matrix | [💚][gh-discussions] | | 🎮️ [Discord Server][✉️discord-invite] | [![Live Chat on Discord][✉️discord-invite-img-ftb]][✉️discord-invite] | [Let's][✉️discord-invite] | [talk][✉️discord-invite] | [about][✉️discord-invite] | [this][✉️discord-invite] | [library!][✉️discord-invite] |

Enterprise Support Tidelift

Available as part of the Tidelift Subscription.

Need enterprise-level guarantees? The maintainers of this and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. [![Get help from me on Tidelift][🏙️entsup-tidelift-img]][🏙️entsup-tidelift] - 💡Subscribe for support guarantees covering _all_ your FLOSS dependencies - 💡Tidelift is part of [Sonar][🏙️entsup-tidelift-sonar] - 💡Tidelift pays maintainers to maintain the software you depend on!
📊`@`Pointy Haired Boss: An [enterprise support][🏙️entsup-tidelift] subscription is "[never gonna let you down][🧮kloc]", and *supports* open source maintainers Alternatively: - [![Live Chat on Discord][✉️discord-invite-img-ftb]][✉️discord-invite] - [![Get help from me on Upwork][👨🏼‍🏫expsup-upwork-img]][👨🏼‍🏫expsup-upwork] - [![Get help from me on Codementor][👨🏼‍🏫expsup-codementor-img]][👨🏼‍🏫expsup-codementor]

✨ Installation

Install the gem and add to the application's Gemfile by executing:

bundle add debug_logging

If bundler is not being used to manage dependencies, install the gem by executing:

gem install debug_logging

⚙️ Configuration

🔧 Basic Usage

Crack open the specs for more complex usage examples than the ones below.

First, how do I turn it off when I need some silence?

For example, in your test suite, before you require "config/environment" or equivalent, do this:

require "logger"
require "debug_logging"

logger = Logger.new($stdout)
logger.level = Logger::UNKNOWN # for silence!
DebugLogging.configuration.logger = logger

It will silence all of the places that have extend DebugLogger, unless those places have overridden the logger config they inherited from the global config.

Without Rails

It just works. ;) Configuration can go anywhere you want. Configuration is the same regardless; see below.

With Rails

Recommend creating config/initializers/debug_logging.rb, or adding to config/application.rb with:

# Showing the defaults
DebugLogging.configuration.logger = Logger.new($stdout) # you probably want to override to be the Rails.logger, and if so you can't set it in the initializer, as it needs to be set after Rails.logger is set.
DebugLogging.configuration.log_level = :debug # at what level are the messages created by this gem sent at?
DebugLogging.configuration.multiple_last_hashes = false # pass every hash argument to last_hash_to_s_proc?
DebugLogging.configuration.last_hash_to_s_proc = nil # e.g. ->(hash) { "keys: #{hash.keys}" }
DebugLogging.configuration.last_hash_max_length = 1_000
DebugLogging.configuration.args_to_s_proc = nil # e.g. ->(*record) { "record id: #{record.first.id}" }
DebugLogging.configuration.args_max_length = 1_000
DebugLogging.configuration.instance_benchmarks = false
DebugLogging.configuration.class_benchmarks = false
DebugLogging.configuration.active_support_notifications = false
DebugLogging.configuration.colorized_chain_for_method = false # e.g. ->(colorized_string) { colorized_string.red.on_blue.underline }
DebugLogging.configuration.colorized_chain_for_class = false # e.g. ->(colorized_string) { colorized_string.colorize(:light_blue ).colorize( :background => :red) }
DebugLogging.configuration.add_invocation_id = true # identify a method call uniquely in a log, pass a proc for colorization, e.g. ->(colorized_string) { colorized_string.light_black }
DebugLogging.configuration.time_formatter_proc = DebugLogging::Constants::DEFAULT_TIME_FORMATTER
DebugLogging.configuration.add_timestamp = false
DebugLogging.configuration.ellipsis = " ✂️ …".freeze
DebugLogging.configuration.mark_scope_exit = true # Only has an effect if benchmarking is off, since benchmarking always marks the scope exit
DebugLogging.configuration.add_payload = false # or a proc which will be called to print the payload
DebugLogging.configuration.payload_max_length = 1000
DebugLogging.configuration.error_handler_proc = nil # e.g. ->(error, config, obj, method_name, *args, **kwargs) { config.log { "#{error.class}: #{error.message} in #{method_name}\nargs: #{args.inspect}" } }

If you prefer to use the block style:

DebugLogging.configure do |config|
  config.logger = Logger.new($stdout) # probably want to override to be the Rails.logger, and if so you can't set it in the initializer, as it needs to be set after Rails.logger is set.
  config.log_level = :debug # at what level do the messages created by this gem sent at?
  config.multiple_last_hashes = false # pass every hash argument to last_hash_to_s_proc?
  config.last_hash_to_s_proc = nil # e.g. ->(hash) { "keys: #{hash.keys}" }
  config.last_hash_max_length = 1_000
  config.args_to_s_proc = nil # e.g. ->(*record) { "record id: #{record.first.id}" }
  config.args_max_length = 1_000
  config.instance_benchmarks = false
  config.class_benchmarks = false
  config.active_support_notifications = false
  config.colorized_chain_for_method = false # e.g. ->(colorized_string) { colorized_string.red.on_blue.underline }
  config.colorized_chain_for_class = false # e.g. ->(colorized_string) { colorized_string.colorize(:light_blue ).colorize( :background => :red) }
  config.time_formatter_proc = DebugLogging::Constants::DEFAULT_TIME_FORMATTER
  config.add_timestamp = false
  config.add_invocation_id = true # identify a method call uniquely in a log, pass a proc for colorization, e.g. ->(colorized_string) { colorized_string.light_black }
  config.ellipsis = " ✂️ …".freeze
  config.mark_scope_exit = true # Only has an effect if benchmarking is off, since benchmarking always marks the scope exit
  config.add_payload = false # or a proc which will be called to print the payload
  config.payload_max_length = 1000
  config.error_handler_proc = nil # e.g. ->(error, config, obj, method_name, *args, **kwargs) { config.log { "#{error.class}: #{error.message} in #{method_name}\nargs: #{args.inspect}" } }
end

All of the above config is inheritable and configurable at the per-class level as well! Just prepend debug_ to any config value you want to override in a class.

All of the above config is inheritable and configurable at the per-instance level as well! Just prepend debug_ to any config value you want to override on an instance of a class.

All of the above config is inheritable and configurable at the per-method level as well! Just send along a hash of the config options, similar to the following:

  • logged :drive, { ellipsis: " ✂️ it out" }
  • i_logged [:drive, :stop], { ellipsis: " ✂️ 2 much" }
  • notified :drive, { ellipsis: " ✂️ it out" }
  • i_notified [:drive, :stop], { ellipsis: " ✂️ 2 much" }

See the example class below, and the specs.

NOTE ON Rails.logger - It will probably be nil in your initializer, so setting the config.logger to Rails.logger there will result in setting it to nil, which means the default will end up being used: Logger.new($stdout). Instead just config the logger in your application.rb, or anytime later, but before your classes get loaded and start inheriting the config:

DebugLogging.configuration.logger = Rails.logger

Every time a method is called, you can now get logs, optionally with arguments, a benchmark, and a unique invocation identifier:

class Car
  # Adds the helper methods to the class.
  #   All helpers prefixed with debug_*,
  #   except for the *logged* decorator, which comes from extending DebugLogging::ClassLogger
  extend DebugLogging

  # per class configuration overrides!
  self.debug_class_benchmarks = true
  self.debug_instance_benchmarks = true

  # For class methods
  #   Provides the versatile `logged` method decorator / macro
  extend DebugLogging::ClassLogger
  # For instance methods
  #   Provides the versatile `i_logged` method decorator / macro
  extend DebugLogging::InstanceLogger

  # == BEGIN CLASS METHODS ==
  # For class methods:
  # Option 1: Use *logged* as a method decorator
  class << self
    def make
      new
    end

    def design(*_args)
      new
    end

    def safety(*_args)
      new
    end

    def dealer_options(*_args)
      new
    end

    def will_not_be_logged
      false
    end
  end
  logged :make

  # Option 2: Use *logged* as a macro
  logged :design, :safety
  # Override configuration options for any class method(s), by passing a hash as the last argument
  # In the last hash any non-Configuration keys will be data that gets logged,
  #     and also made available to last_hash_to_s_proc
  logged :dealer_options, {
    something: "here", # <= will be logged, and available to last_hash_to_s_proc
    multiple_last_hashes: true, # <= Overrides config
    error_handler_proc: nil, # NOTE: if you define the error_handler_proc inside a class like this you can use self inside the proc to refer to the class the method was called on!
  }
  # == END CLASS METHODS ==

  # == BEGIN INSTANCE METHODS ==
  # For instance methods:
  # Option 1: specify the exact method(s) to add logging to, and optionally customize
  i_notified [
    :drive,
    :stop,
    [:turn, {instance_variables: %i[direction angle]}],
  ]

  def drive(speed)
    speed
  end

  def stop(**_opts)
    0
  end

  # For instance methods:
  # Option 2: add logging to all instance methods defined above (but *not* defined below)
  i_logged instance_methods(false)

  def faster(**_opts)
    5
  end

  # Override configuration options for any instance method(s), by passing a hash as the last argument
  # In the last hash any non-Configuration keys will be data that gets logged,
  #     and also made available to last_hash_to_s_proc
  # Here's an example that sets every possible option, while also showing what the default values are!
  i_logged [:faster], {
    logger: Logger.new($stdout), # probably want to override to be the Rails.logger
    log_level: :debug, # at what level do the messages created by this gem sent at?
    multiple_last_hashes: false,
    last_hash_to_s_proc: nil, # e.g. ->(hash) { "keys: #{hash.keys}" }
    last_hash_max_length: 1_000,
    args_to_s_proc: nil, # e.g. ->(*record) { "record id: #{record.first.id}" }
    args_max_length: 1_000,
    colorized_chain_for_method: false, # e.g. ->(colorized_string) { colorized_string.red.on_blue.underline }
    colorized_chain_for_class: false,  # e.g. ->(colorized_string) { colorized_string.colorize(:light_blue ).colorize( :background => :red) }
    add_invocation_id: true, # allows unique identification of method call; association of entry and exit log lines
    ellipsis: " ✂️ …".freeze,
    mark_scope_exit: false,
    add_payload: true, # Can also be a proc returning a string, which will be called when printing the payload
    payload_max_length: 1_000,
    error_handler_proc: nil, # NOTE: if you define the error_handler_proc inside a class like this you can use self inside the proc to refer to the instance of the class the method was called on!
    time_formatter_proc: DebugLogging::Constants::DEFAULT_TIME_FORMATTER,
    add_timestamp: false,
    instance_benchmarks: false,
    class_benchmarks: false,
  }

  # You can also use `i_logged` as a true method decorator:
  i_logged def slower
    2
  end

  def will_not_be_logged
    false
  end
  # == END INSTANCE METHODS ==
end

ActiveSupport::Notifications integration

To use ActiveSupport::Notifications integration, enable active_support_notifications in the config, either single line or block style:

DebugLogging.configuration.active_support_notifications = true

or

DebugLogging.configure do |config|
  config.active_support_notifications = true
end

Every time a method is called, class and instance method events are instrumented, consumed and logged:

class Car
  # Adds the helper methods to the class.
  #   All helpers prefixed with debug_*,
  #   except for the *notified* decorator, which comes from extending DebugLogging::ClassNotifier
  extend DebugLogging
  # For instance methods
  #   Provides the versatile `i_notified` method decorator / macro
  extend DebugLogging::InstanceNotifier
  # For class methods
  #   Provides the versatile `notified` method decorator / macro
  extend DebugLogging::ClassNotifier

  # For instance methods:
  # Option 1: specify the exact method(s) to add instrumentation to
  #   NOTE: You can capture instance variable values as part of the event payload
  i_notified [
    :drive,
    :stop,
    [:turn, {instance_variables: %i[direction angle]}],
  ]

  # == BEGIN CLASS METHODS ==
  # For class methods:
  # Option 1: Use *notified* as a method decorator
  class << self
    def make
      new
    end

    def design(*_args)
      new
    end

    def safety(*_args)
      new
    end

    def dealer_options(*_args)
      new
    end

    def will_not_be_notified
      false
    end
  end
  notified :make

  # Option 2: Use *logged* as a macro
  notified :design, :safety
  # Override configuration options for any class method(s), by passing a hash as the last argument
  # In the last hash any non-Configuration keys will be data that gets added to the event payload,
  #     and also made available to last_hash_to_s_proc
  notified :dealer_options, {
    something: "here", # <== will be added to the event payload, and be available to last_hash_to_s_proc
    add_invocation_id: false, # <== Overrides config
  }
  # == END CLASS METHODS ==

  # == BEGIN INSTANCE METHODS ==
  def drive(speed)
    speed
  end

  def stop(**_opts)
    0
  end

  # For instance methods:
  # Option 2: add notification instrumentation to all instance methods defined above (but *not* defined below)
  i_notified instance_methods(false)

  def faster(**_opts)
    0
  end

  # Override options for any instance method(s), by passing a hash as the last argument
  # In the last hash any non-Configuration keys will be data that gets added to the event payload,
  #     and also made available to last_hash_to_s_proc
  i_notified [:faster], {add_invocation_id: false}

  def will_not_be_notified
    false
  end
  # == END INSTANCE METHODS ==
end

🦷 FLOSS Funding

While galtzo-floss tools are free software and will always be, the project would benefit immensely from some funding. Raising a monthly budget of... "dollars" would make the project more sustainable.

We welcome both individual and corporate sponsors! We also offer a wide array of funding channels to account for your preferences. Currently, Open Collective is our preferred funding platform.

If you're working in a company that's making significant use of galtzo-floss tools we'd appreciate it if you suggest to your company to become a galtzo-floss sponsor.

You can support the development of galtzo-floss tools via GitHub Sponsors, Liberapay, PayPal, Open Collective and Tidelift.

📍 NOTE
If doing a sponsorship in the form of donation is problematic for your company
from an accounting standpoint, we'd recommend the use of Tidelift,
where you can get a support-like subscription instead.

Open Collective for Individuals

Support us with a monthly donation and help us continue our activities. [Become a backer]

NOTE: kettle-readme-backers updates this list every day, automatically.

No backers yet. Be the first!

Open Collective for Organizations

Become a sponsor and get your logo on our README on GitHub with a link to your site. [Become a sponsor]

NOTE: kettle-readme-backers updates this list every day, automatically.

No sponsors yet. Be the first!

Another way to support open-source

I’m driven by a passion to foster a thriving open-source community – a space where people can tackle complex problems, no matter how small. Revitalizing libraries that have fallen into disrepair, and building new libraries focused on solving real-world challenges, are my passions. I was recently affected by layoffs, and the tech jobs market is unwelcoming. I’m reaching out here because your support would significantly aid my efforts to provide for my family, and my farm (11 🐔 chickens, 2 🐶 dogs, 3 🐰 rabbits, 8 🐈‍ cats).

If you work at a company that uses my work, please encourage them to support me as a corporate sponsor. My work on gems you use might show up in bundle fund.

I’m developing a new library, floss_funding, designed to empower open-source developers like myself to get paid for the work we do, in a sustainable way. Please give it a look.

Floss-Funding.dev: 👉️ No network calls. 👉️ No tracking. 👉️ No oversight. 👉️ Minimal crypto hashing. 💡 Easily disabled nags

OpenCollective Backers OpenCollective Sponsors Sponsor Me on Github Liberapay Goal Progress Donate on PayPal Buy me a coffee Donate on Polar Donate to my FLOSS efforts at ko-fi.com Donate to my FLOSS efforts using Patreon

🔐 Security

See SECURITY.md.

🤝 Contributing

If you need some ideas of where to help, you could work on adding more code coverage, or if it is already 💯 (see below) check issues or PRs, or use the gem and think about how it could be better.

We Keep A Changelog so if you make changes, remember to update it.

See CONTRIBUTING.md for more detailed instructions.

🚀 Release Instructions

See CONTRIBUTING.md.

Code Coverage

Coverage service badges [![Coverage Graph][🏀codecov-g]][🏀codecov] [![Coveralls Test Coverage][🏀coveralls-img]][🏀coveralls] [![QLTY Test Coverage][🏀qlty-covi]][🏀qlty-cov]

🪇 Code of Conduct

Everyone interacting with this project's codebases, issue trackers, chat rooms and mailing lists agrees to follow the Contributor Covenant 2.1.

🌈 Contributors

Contributors

Made with contributors-img.

Also see GitLab Contributors: https://gitlab.com/galtzo-floss/debug_logging/-/graphs/main

⭐️ Star History Star History Chart

📌 Versioning

This library follows Semantic Versioning 2.0.0 for its public API where practical. For most applications, prefer the Pessimistic Version Constraint with two digits of precision.

For example:

spec.add_dependency("debug_logging", "~> 4.0")
📌 Is "Platform Support" part of the public API? More details inside. Dropping support for a platform can be a breaking change for affected users. If a release changes supported platforms, it should be called out clearly in the changelog and versioned with that impact in mind. To get a better understanding of how SemVer is intended to work over a project's lifetime, read this article from the creator of SemVer: - ["Major Version Numbers are Not Sacred"][📌major-versions-not-sacred]

See CHANGELOG.md for a list of releases.

📄 License

The gem is available as open source under the terms of the MIT License: MIT.

See LICENSE.md for the official copyright notice.

Copyright holders - Copyright (c) 2017-2018, 2020-2021, 2023-2024, 2026 Peter H. Boling - Copyright (c) 2020 John Gillson - Copyright (c) 2024 Aboling0

🤑 A request for help

Maintainers have teeth and need to pay their dentists. After getting laid off in an RIF in March, and encountering difficulty finding a new one, I began spending most of my time building open source tools. I'm hoping to be able to pay for my kids' health insurance this month, so if you value the work I am doing, I need your support. Please consider sponsoring me or the project.

To join the community or get help 👇️ Join the Discord.

Live Chat on Discord

To say "thanks!" ☝️ Join the Discord or 👇️ send money.

Sponsor galtzo-floss/debug_logging on Open Source Collective 💌 Sponsor me on GitHub Sponsors 💌 Sponsor me on Liberapay 💌 Donate on PayPal

Please give the project a star ⭐ ♥.

Thanks for RTFM. ☺️

Field Value
Package debug_logging
Description 🪲 Unobtrusive debug logging for Ruby. NO LITTERING.
Automatically log selected methods and their arguments as they are called at runtime!
Homepage https://github.com/galtzo-floss/debug_logging
Source https://github.com/galtzo-floss/debug_logging/tree/v4.0.3
License MIT
Funding https://github.com/sponsors/pboling, https://issuehunt.io/u/pboling, https://ko-fi.com/pboling, https://liberapay.com/pboling/donate, https://opencollective.com/pboling, https://patreon.com/galtzo, https://polar.sh/pboling, https://thanks.dev/u/gh/pboling, https://tidelift.com/funding/github/rubygems/debug_logging, https://www.buymeacoffee.com/pboling