python-coloredlogs

repository·master·Indexed 20 days ago

https://github.com/xolox/python-coloredlogs

A Python package that provides colored terminal output for the standard logging module using ANSI escape sequences. It includes a custom Formatter to enhance log readability based on log levels, a CLI tool to convert command output to HTML, and support for custom log format fields like hostname, program name, and username.

Tokens
1.8K
Snippets
8
Records
12
Agent score
69%

What's inside coloredlogs

  1. Install coloredlogs for terminal output

    master

    The primary entry point for using coloredlogs is the coloredlogs.install() function. By default, calling install() attaches a handler to the root logger, which means log messages from both your application code and any third-party libraries will be colored in the terminal.

    If you want to restrict colored output to only your application's logs and ignore library logs, pass your specific logger object to the install() function instead of calling it without arguments.

    import logging
    import coloredlogs
    
    # Option 1: Install on the root logger (shows everything)
    coloredlogs.install()
    
    # Option 2: Install on a specific logger (shows only your app logs)
    logger = logging.getLogger(__name__)
    coloredlogs.install(logger=logger)
  2. Get colored output from cron jobs

    master

    When running in a cron job, coloredlogs detects the lack of an interactive terminal and suppresses ANSI escape sequences. To receive colored HTML emails from cron, use one of these two methods:

    Method 1: Modifying your crontab

    Use the coloredlogs CLI tool to wrap your command. This uses the script program to trick the command into thinking it is in an interactive terminal, then converts the output to HTML.

    MAILTO="your-email-address@here"
    CONTENT_TYPE="text/html"
    * * * * * root coloredlogs --to-html your-command

    Method 2: Modifying your Python code

    Use the ColoredCronMailer context manager. This requires the capturer package, which can be installed via the [cron] extra.

    $ pip install 'coloredlogs[cron]'
  3. Enable millisecond precision in timestamps

    master

    By default, coloredlogs does not include milliseconds in timestamps. You can enable them using one of three methods:

    1. The easy way: Pass milliseconds=True to coloredlogs.install().
    2. Custom format: Include %(msecs)03d in the fmt argument of coloredlogs.install().
    3. Date/time directive: Add %f to your date/time format string (supported in version 9.3+).
    # Method 1: Using the milliseconds argument
    coloredlogs.install(milliseconds=True)
    
    # Method 2: Using a custom format string
    coloredlogs.install(fmt='%(asctime)s,%(msecs)03d %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s')
  4. Use coloredlogs.install() to enable colored logging

    master

    The coloredlogs.install() function configures your logging output.

    By default, calling coloredlogs.install() without arguments installs a handler on the root logger, meaning log messages from your code and all imported libraries will be colored in the terminal.

    To restrict colored output to only your specific application code, pass a specific logger instance to the logger parameter.

    import coloredlogs, logging
    
    # Create a logger object.
    logger = logging.getLogger(__name__)
    
    # Option 1: Install on the root logger (shows logs from all libraries)
    coloredlogs.install(level='DEBUG')
    
    # Option 2: Install on a specific logger (shows only logs from this logger)
    coloredlogs.install(level='DEBUG', logger=logger)
    
    # Examples
    logger.debug("this is a debugging message")
    logger.info("this is an informational message")
    logger.warning("this is a warning message")
    logger.error("this is an error message")
    logger.critical("this is a critical message")
  5. Use ColoredFormatter for custom log formatting

    master
    The coloredlogs.ColoredFormatter class allows you to create custom log formatters that include color coding. This is useful when you want more control over how logs are presented than the default install() behavior provides.
  6. Use custom log format fields

    master

    The ColoredFormatter supports several custom fields that are automatically populated via internal filters when detected in your format string:

    • %(hostname)s: The hostname of the local system.
    • %(programname)s: The name of the currently running program.
    • %(username)s: The username of the currently logged-in user.
  7. Reference: coloredlogs CLI options

    master

    The following options are available for the coloredlogs command-line interface:

    -c, --convert, --to-html
        Capture the output of an external command (given by the positional
        arguments) and convert ANSI escape sequences in the output to HTML.
    
    -d, --demo
        Perform a simple demonstration of the coloredlogs package to show
        the colored logging on an interactive terminal.
    
    -h, --help
        Show this message and exit.
  8. Convert command output to HTML with the coloredlogs CLI

    master

    The coloredlogs CLI can capture the output of an external command and convert its ANSI escape sequences into HTML. This is useful for viewing colored terminal output in a web browser or saving it to an HTML file.

    Behavior:

    • If run in an interactive terminal, the tool will write the generated HTML to a temporary file and automatically open it in your default web browser.
    • If not in an interactive terminal (e.g., in a cron job or piped output), the generated HTML will be written to standard output (stdout).
    • To ensure ANSI escape sequences are captured, the tool uses the script program to emulate an interactive terminal.
    • If the command produces no output, no HTML is produced to avoid empty files/emails.
    coloredlogs --convert <command> [args]
    # OR
    coloredlogs --to-html <command> [args]