python-colorlog

repository·main·Indexed 21 days ago

https://github.com/borntyping/python-colorlog

A library that adds color support to Python's standard logging module. It provides a ColoredFormatter and StreamHandler that allow developers to use color escape codes and level-based tokens in log format strings to improve terminal readability.

Tokens
1.5K
Snippets
7
Records
9
Agent score
26%

What's inside python-colorlog

  1. Use color escape codes in format strings

    main

    You can inject colors into your format strings using specific tokens:

    Level-based tokens

    • log_color: Returns the color associated with the current log record's level.
    • <name>_log_color: Returns a secondary color based on the log level (requires secondary_log_colors configuration).

    Formatting tokens

    • {color}, fg_{color}, bg_{color}: Foreground and background colors.
    • bold, bold_{color}, fg_bold_{color}, bg_bold_{color}: Bold/bright colors.
    • thin, thin_{color}, fg_thin_{color}: Thin colors (terminal dependent).
    • reset: Clears all formatting.

    Available color names

    • Standard: black, red, green, yellow, blue, purple, cyan, white.
    • Bright: light_black, light_red, light_green, light_yellow, light_blue, light_purple, light_cyan, light_white.
    • 256-color: Use integers 0-255 (e.g., fg_196, bg_42).
  2. Use secondary_log_colors for multiple level-based colors

    main

    The secondary_log_colors argument allows you to define additional color mappings that can be accessed in the format string using the pattern <name>_log_color. This is useful for highlighting different parts of a log line (like the message) with colors that change based on the log level.

    from colorlog import ColoredFormatter
    
    formatter = ColoredFormatter(
    	"%(log_color)s%(levelname)-8s%(reset)s %(message_log_color)s%(message)s",
    	secondary_log_colors={
    		'message': {
    			'ERROR': 'red',
    			'CRITICAL': 'red'
    		}
    	}
    )
  3. Basic usage of colorlog

    main

    To use colorlog, create a colorlog.StreamHandler, set its formatter to colorlog.ColoredFormatter(), and add the handler to your logger.

    import colorlog
    
    handler = colorlog.StreamHandler()
    handler.setFormatter(colorlog.ColoredFormatter())
    
    logger = colorlog.getLogger('example')
    logger.addHandler(handler)
  4. Configure colorlog with dictConfig

    main

    To use colorlog.ColoredFormatter with Python's logging.config.dictConfig, use the () key to specify the class path.

    import logging.config
    
    logging.config.dictConfig({
    	'formatters': {
    		'colored': {
    			'()': 'colorlog.ColoredFormatter',
    			'format': '%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s'
    		}
    	}
    })
  5. Configure colorlog with fileConfig

    main

    In a .ini configuration file used by fileConfig, define a formatter with class=colorlog.ColoredFormatter.

    [formatters]
    keys=color
    
    [formatter_color]
    class=colorlog.ColoredFormatter
    format=%(log_color)s%(levelname)-8s%(reset)s %(bg_blue)s[%(name)s]%(reset)s %(message)s
    datefmt=%m-%d %H:%M:%S
  6. Customize log colors for specific levels

    main

    Pass a dictionary to log_colors in ColoredFormatter to map log levels to specific colors or color combinations (e.g., red,bg_white).

    from colorlog import ColoredFormatter
    
    formatter = ColoredFormatter(
    	"%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s",
    	log_colors={
    		"DEBUG": "cyan",
    		"INFO": "green",
    		"WARNING": "yellow",
    		"ERROR": "red",
    		"CRITICAL": "red,bg_white",
    	}
    )
  7. Use colorlog with custom log levels

    main

    If you add custom log levels using logging.addLevelName, you can map them to colors in ColoredFormatter by including the level name in the log_colors dictionary.

    import logging, colorlog
    TRACE = 5
    logging.addLevelName(TRACE, 'TRACE')
    
    formatter = colorlog.ColoredFormatter(log_colors={'TRACE': 'yellow'})
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    
    logger = logging.getLogger('example')
    logger.addHandler(handler)
    logger.setLevel('TRACE')
    logger.log(TRACE, 'a message using a custom level')
  8. Configure ColoredFormatter arguments

    main

    colorlog.ColoredFormatter extends logging.Formatter and accepts the following additional arguments:

    • fmt (default=None): A format string. If None, a default is selected based on style (e.g., %(log_color)s%(levelname)s:%(name)s:%(message)s for % style).
    • reset (default=True): Implicitly adds a color reset code to the output.
    • log_colors (default=None): A mapping of record level names (e.g., 'DEBUG', 'INFO') to color names.
    • secondary_log_colors (default=None): A mapping of names to log_colors style mappings, allowing additional colors to be used in format strings via <name>_log_color.
    • stream (default=None): The stream used to detect TTY status. Colors are disabled on non-TTY streams unless force_color is set.
    • no_color (default=False): Disables color output. Can also be set via the NO_COLOR environment variable.
    • force_color (default=False): Forces color output even on non-TTY streams. Takes precedence over no_color. Can also be set via the FORCE_COLOR environment variable.
    • datefmt, style, validate, defaults: Passed through to logging.Formatter.