close
close
loguru change message color

loguru change message color

3 min read 07-12-2024
loguru change message color

Changing Loguru Message Colors: A Comprehensive Guide

Loguru is a popular Python logging library known for its beautiful and informative output. But sometimes, the default colors aren't quite right for your needs. This article will guide you through customizing Loguru's message colors to enhance readability and highlight critical information. We'll cover several methods, from simple modifications to more advanced techniques for granular control.

Understanding Loguru's Colorization

Loguru uses ANSI escape codes to color terminal output. These codes aren't directly visible in your text; instead, they instruct your terminal to display the text in a specific color. Loguru's default configuration assigns colors based on log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL).

Method 1: Using the colorize Parameter (Simplest Approach)

The simplest way to control Loguru's colorization is using the colorize parameter during initialization. Setting it to False disables all colorization. However, for more nuanced control, you can use a custom function.

from loguru import logger

def my_color_function(message):
    # Customize your color logic here.  
    # This example colors WARNING messages in yellow, and ERROR messages in red.
    if "WARNING" in message:
      return "\033[93m" + message + "\033[0m"  # Yellow
    elif "ERROR" in message:
      return "\033[91m" + message + "\033[0m"  # Red
    else:
      return message

logger.remove()  #remove the default handler
logger.add(lambda msg: print(my_color_function(msg)), colorize=False) #add a custom handler with colorization

logger.debug("This is a debug message.")
logger.info("This is an info message.")
logger.warning("This is a warning message.")
logger.error("This is an error message.")
logger.critical("This is a critical message.")

This method gives you basic control but requires manual handling of ANSI codes. It's straightforward for simple color adjustments.

Method 2: Leveraging Format Strings and ANSI Codes (Intermediate)

For more precise control, you can directly embed ANSI escape codes within your log message format strings.

from loguru import logger

logger.remove()
logger.add(lambda msg: print(f"\033[92m{msg}\033[0m")) #Green for all messages


logger.debug("This is a debug message.")
logger.info("This is an info message.")
logger.warning("This is a warning message.")
logger.error("This is an error message.")
logger.critical("This is a critical message.")


Remember to always reset the color using \033[0m to avoid unintended color bleed into subsequent output. This approach requires a deeper understanding of ANSI escape codes but offers significant flexibility.

Method 3: Creating a Custom Handler (Advanced)

For the most advanced control, you can create a custom Loguru handler. This provides the greatest level of customization.

from loguru import logger

class ColoredHandler:
    def __init__(self):
        self.colors = {
            "DEBUG": "\033[94m",  # Blue
            "INFO": "\033[92m",  # Green
            "WARNING": "\033[93m",  # Yellow
            "ERROR": "\033[91m",  # Red
            "CRITICAL": "\033[91m", # Red
        }
        self.reset = "\033[0m"

    def __call__(self, message):
        record = message.record
        level = record["level"].name
        color = self.colors.get(level, "")  # Default to no color if level isn't found
        colored_message = color + record["message"] + self.reset
        print(colored_message)


logger.remove()
logger.add(ColoredHandler())

logger.debug("This is a debug message.")
logger.info("This is an info message.")
logger.warning("This is a warning message.")
logger.error("This is an error message.")
logger.critical("This is a critical message.")

This example creates a handler that maps log levels to specific colors. This is a robust approach for complex scenarios.

Choosing the Right Method

The best method depends on your needs:

  • Method 1: Ideal for simple toggling of colorization or minor adjustments.
  • Method 2: Suitable for intermediate customization where you want precise control over individual messages.
  • Method 3: Best for complex scenarios requiring granular control and sophisticated color mapping based on log levels or other criteria.

Remember to consult the Loguru documentation for the most up-to-date information and further customization options. By understanding these methods, you can tailor Loguru's output to perfectly suit your logging needs and improve the overall readability of your application logs.

Related Posts


Popular Posts