We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
If you're like me, a light sprinkling of color helps make your log output clearer and more engaging. Fortunately,
Elixir's Logger
module allows you to easily add color to your log messages using the ansi_color
metadata option.
Adding color to log messages
The ansi_color
option lets you choose a color for your log messages from a set of predefined options. Here's how you
can add some flair to your logs:
# Available color options:
# [:black, :red, :green, :yellow, :blue, :magenta, :cyan, :white]
#
# You can also use lighter shades by prefixing the color with :light_
#
Logger.info("a blue message", ansi_color: :blue)
Logger.info("a light green message", ansi_color: :light_green)
As you can see, it's pretty simple to highlight important log messages by adding a dash of color. The available color options are flexible, even allowing you to use lighter shades for better visibility.
Background colors
Need to add some background color? No problem! The ansi_color
option supports background colors too, like so:
Logger.info("message with blue background", ansi_color: :blue_background)
However, there's one little catch. It seems like you can't combine both foreground and background colors using just
ansi_color
. For example, you might think the following code would give you a white foreground on a blue background:
Logger.info("message", ansi_color: :white, ansi_color: :blue_background)
But unfortunately, Elixir will only apply the last specified color, so in this case, it'll pick the background color and ignore the foreground.
Workaround for foreground and background colors
If you really want to mix both foreground and background colors, you can take a different approach using IO.ANSI
.
Here's how you can manually combine colors:
Logger.debug(IO.ANSI.red_background() <> IO.ANSI.blue() <> "my message")
This way, you get full control over both the text and the background color.
Final thoughts
For now, combining foreground and background colors using ansi_color
'' supported directly, but using IO.ANSI
offers
a handy workaround. In any case, adding color to your logs is a simple yet powerful way to make them more readable and
highlight important information at a glance. Happy logging!
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.