Last active
January 8, 2025 07:07
-
-
Save kyrylo/3d90f7a656d1a0accf244b8f1d25999b to your computer and use it in GitHub Desktop.
Nice colorized logs for Rails apps! With this initializer, you can instantly colorize your Rails development logs. Just copy and paste the code, and it’ll work. https://x.com/kyrylosilin/status/1852308566201237815
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# config/initializers/colorized_logger.rb | |
# This initializer adds color to the Rails logger output. It's a nice way to | |
# visually distinguish log levels. | |
module ColorizedLogger | |
COLOR_CODES = { | |
debug: "\e[36m", # Cyan | |
info: "\e[32m", # Green | |
warn: "\e[33m", # Yellow | |
error: "\e[31m", # Red | |
fatal: "\e[35m", # Magenta | |
unknown: "\e[37m" # White (or terminal default) | |
}.freeze | |
RESET = "\e[0m" | |
def debug(progname = nil, &block) | |
super(colorize(:debug, progname, &block)) | |
end | |
def info(progname = nil, &block) | |
super(colorize(:info, progname, &block)) | |
end | |
def warn(progname = nil, &block) | |
super(colorize(:warn, progname, &block)) | |
end | |
def error(progname = nil, &block) | |
super(colorize(:error, progname, &block)) | |
end | |
def fatal(progname = nil, &block) | |
super(colorize(:fatal, progname, &block)) | |
end | |
def unknown(progname = nil, &block) | |
super(colorize(:unknown, progname, &block)) | |
end | |
private | |
def colorize(level, message, &block) | |
"#{COLOR_CODES[level]}#{message || (block && block.call)}#{RESET}" | |
end | |
end | |
Rails.logger.extend(ColorizedLogger) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@navidemad If you like code golfing, here's an even shorter version: