How to use colored logs in Rails for better visibility in the console
Colored Logs in Rails
Rails logger supports colored output in the console by using ANSI escape codes. This can help you quickly identify warnings, errors, or other important messages during development. Rails logger supports colored output in the console by using ANSI escape codes. This can help you quickly identify warnings, errors, or other important messages during development.
Example: Adding Color to Logs
You can add foreground and background colors to your log messages like this:
# Yellow text
Rails.logger.warn("\e[33mThis is a yellow warning message\e[0m")
# Red text with yellow background
Rails.logger.error("\e[31;43mThis is an error with a yellow background\e[0m")
\e[33msets the text color to yellow.\e[31;43msets the text color to red and the background to yellow.\e[0mresets the color to default.
Note: Colors will only appear in the console (stdout), not in log files. Log files will contain the raw escape codes as plain text.
Common ANSI Color Codes
| Code | Effect |
|---|---|
\e[31m |
Red text |
\e[33m |
Yellow text |
\e[41m |
Red background |
\e[43m |
Yellow background |
\e[0m |
Reset to default |
Use colored logs to make important messages stand out during development!