← All writing

ColoredLogger - prints logs in color to the console and records to files

This document introduces a logger class called ColoredLogger, which can print logs in different colors according to different message types and log to a file. This class uses the colorama library to display colored text in the console. In order to make the console output logs easier to read and understand, we usually use colored output. At the same time, recording logs to files can facilitate our subsequent debugging and analysis. In Python, we can use the logging and colorama libraries to achieve such functionality.

阅读中文版 →

Print logs in color to the console and log to files

This document introduces a logger class called ColoredLogger, which can print logs in different colors according to different message types and log to a file. This class uses the colorama library to display colored text in the console. In order to make the console output logs easier to read and understand, we usually use colored output. At the same time, recording logs to files can facilitate our subsequent debugging and analysis. In Python we can useloggingandcoloramalibrary to implement such functionality.

The following is a detailed introduction on how to use these two libraries.

Function

  • Log messages can be printed in different colors based on different message types.
  • Log messages to a file using the standard logging module to record.
  • Displays colored log messages in the console.

Principle

loggingThe library provides powerful logging functionality, allowing us to log to the console, file, or other output device, and provides detailed configuration options.

coloramaThe library allows us to output colored text to the console. It provides support for ANSI color coding and can be used in almost all platforms and terminals.

Let's initialize firstcolorama, and then defined aColoredLoggerClass, which contains various colored output styles and corresponding log levels. Then, we setloggingThe configuration defines the log output level, output file and file mode. Finally, we useColoredLoggeroflogMethod to record logs, it will simultaneously output colored text to the console and write it to the file after removing the color control characters.
ColoredLogger class uses colorama Library to set color output in the console. It works by defining colors for different types of messages and using Fore and Style class to apply the corresponding color.

ColoredLogger class log The method accepts two parameters:msg_type and msg. According to msg_type The value of the parameter, the method will select the appropriate color and print a message with the color to the console. It then uses a regular expression to remove the color control characters and uses logging.info Method logs an uncolored message to a file.

How to use

  1. Installation colorama library, use the following command:

    1
    pip install colorama
  2. Import the required modules and classes:

    1
    2
    3
    import re
    import logging
    from colorama import init, Fore, Style
  3. initialization colorama

    1
    init(autoreset=True)
  4. definition ColoredLogger class, and set the colors for different types of messages. For example:

    1
    2
    3
    4
    5
    6
    7
    8
    class ColoredLogger:
    def __init__(self):
    self.type_A = Fore.CYAN + Style.BRIGHT
    self.type_B = Fore.GREEN + Style.BRIGHT
    self.type_C = Fore.YELLOW + Style.BRIGHT
    self.type_D = Fore.MAGENTA + Style.BRIGHT
    self.type_E = Fore.BLUE + Style.BRIGHT
    self.RESET = Style.RESET_ALL
  5. Instantiate ColoredLogger class and use log Method prints and logs messages. For example:

    1
    2
    3
    4
    logger = ColoredLogger()
    logger.log('type_A', 'This is a test message for type A.')
    logger.log('type_B', 'This is a test message for type B.')
    # ...
  6. Configure the logger to write log messages to a file with the following command:

    1
    logging.basicConfig(level=logging.INFO, filename='example.log', filemode='w')
  7. Run the code to see colored log messages displayed on the console and in the file.

Complete code implementation

import re
import logging
from colorama import init, Fore, Style

# Initialize colorama
init(autoreset=True)

class ColoredLogger:

    def __init__(self):
        self.type_A = Fore.CYAN + Style.BRIGHT
        self.type_B = Fore.GREEN + Style.BRIGHT
        self.type_C = Fore.YELLOW + Style.BRIGHT
        self.type_D = Fore.MAGENTA + Style.BRIGHT
        self.type_E = Fore.BLUE + Style.BRIGHT
        self.RESET = Style.RESET_ALL

    def log(self, msg_type, msg):
        if msg_type == "type_A":
            self.print_and_log(self.type_A + f"type_A: {msg}" + self.RESET)
        elif msg_type == "type_B":
            self.print_and_log(self.type_B + f"type_B: {msg}" + self.RESET)
        elif msg_type == "type_C":
            self.print_and_log(self.type_C + f"type_C: {msg}" + self.RESET)
        elif msg_type == "type_D":
            self.print_and_log(self.type_D + f"type_D: {msg}" + self.RESET)
        elif msg_type == "type_E":
            self.print_and_log(self.type_E + f"type_E: {msg}" + self.RESET)

    def print_and_log(self, msg):
        # Print to console with color
        print(msg)

        # Remove color control chars for logging to file
        msg_without_color = re.sub('\x1b\[[0-9;]*m', '', msg)
        logging.info(msg_without_color)

# Setup logging configuration
logging.basicConfig(level=logging.INFO, filename='example.log', filemode='w')

# Use the ColoredLogger
logger = ColoredLogger()
logger.log('type_A', 'This is a test message for type A.')
logger.log('type_B', 'This is a test message for type B.')
logger.log('type_C', 'This is a test message for type C.')
logger.log('type_D', 'This is a test message for type D.')
logger.log('type_E', 'This is a test message for type E.')
```![Alt text](image.png)

## 注意事项
1. `colorama`库的颜色和样式可能在不同的平台和终端上有不同的效果,所以需要在目标环境上进行测试。
2. 在写入文件时,需要去除颜色控制字符,否则会在文本中留下一些无法识别的字符。
3. 在设置`logging`的配置时,需要注意文件模式的设置。'w'模式会在每次运行时覆盖之前的日志,而'a'模式则会在之前的日志后追加新的日志。
4. 使用`logging`库记录日志时,需要注意日志的级别。不同级别的日志会有不同的输出效果和记录方式。
5. 需要注意线程安全。如果在多线程环境下使用`logging`库,可能需要额外的配置来保证线程安全。