### Basic Logging Setup with Colorlog Source: https://github.com/borntyping/python-colorlog/blob/main/README.md Set up a basic logging configuration using colorlog's StreamHandler and ColoredFormatter. This example demonstrates how to attach a handler with a custom formatter to a logger. ```python import colorlog handler = colorlog.StreamHandler() handler.setFormatter(colorlog.ColoredFormatter( '%(log_color)s%(levelname)s:%(name)s:%(message)s')) logger = colorlog.getLogger('example') logger.addHandler(handler) ``` -------------------------------- ### Install colorlog Source: https://github.com/borntyping/python-colorlog/blob/main/README.md Install the colorlog library using pip. This command is used for system-wide or virtual environment installation. ```bash pip install colorlog ``` -------------------------------- ### Basic Setup with basicConfig Source: https://context7.com/borntyping/python-colorlog/llms.txt Configure colorlog for basic colored output using the logging.basicConfig function. This is suitable for simple applications where a single handler and formatter are sufficient. ```python import colorlog colorlog.basicConfig( level=colorlog.DEBUG, format="%(log_color)s%(levelname)-8s%(reset)s %(message)s", log_colors={ "DEBUG": "cyan", "INFO": "green", "WARNING": "yellow", "ERROR": "red", "CRITICAL": "bold_red", } ) colorlog.debug("Debug message") colorlog.info("Info message") colorlog.warning("Warning message") colorlog.error("Error message") colorlog.critical("Critical message") import logging logger = logging.getLogger("myapp") logger.info("This will also be colored") ``` -------------------------------- ### Loading YAML Configuration Source: https://context7.com/borntyping/python-colorlog/llms.txt Load logging configuration from a YAML file using logging.config.dictConfig and PyYAML. Ensure PyYAML is installed (`pip install PyYAML`). ```python import logging.config import pathlib import yaml config_path = pathlib.Path("logging.yaml") logging.config.dictConfig(yaml.safe_load(config_path.read_text())) root = logging.getLogger() root.info("Root logger with colors") app = logging.getLogger("application") app.warning("Application logger") ``` -------------------------------- ### Custom ColoredFormatter Configuration Source: https://github.com/borntyping/python-colorlog/blob/main/README.md Create a ColoredFormatter with custom log colors and message formatting. This example shows how to define specific colors for different log levels and customize the output string. ```python from colorlog import ColoredFormatter formatter = ColoredFormatter( '%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s', datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', }, secondary_log_colors={}, style='%' ) ``` -------------------------------- ### Using custom log levels with ColoredFormatter Source: https://github.com/borntyping/python-colorlog/blob/main/README.md Demonstrates how to use a custom log level 'TRACE' with colorlog. Requires importing logging and colorlog, defining the level, and setting up a handler and logger. ```python 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') ``` -------------------------------- ### basicConfig Replacement Source: https://context7.com/borntyping/python-colorlog/llms.txt Use colorlog's basicConfig as a drop-in replacement for the standard logging.basicConfig() to automatically configure colored output. ```python import colorlog ``` -------------------------------- ### Configuration with dictConfig Source: https://context7.com/borntyping/python-colorlog/llms.txt Configure colorlog using Python's dictionary-based logging configuration. This method provides granular control over formatters, handlers, and loggers. ```python import logging import logging.config logging.config.dictConfig({ "version": 1, "disable_existing_loggers": False, "formatters": { "colored": { "()": "colorlog.ColoredFormatter", "format": "% (log_color)s% (asctime)s - % (name) -11s - % (levelname) -8s - % (message)s", "log_colors": { "DEBUG": "cyan", "INFO": "green", "WARNING": "yellow", "ERROR": "red", "CRITICAL": "bold_red", } } }, "handlers": { "console": { "class": "logging.StreamHandler", "level": "DEBUG", "formatter": "colored", "stream": "ext://sys.stdout" } }, "root": { "level": "DEBUG", "handlers": ["console"] } }) logger = logging.getLogger("application") logger.debug("Debug from dictConfig") logger.info("Info from dictConfig") logger.warning("Warning from dictConfig") logger.error("Error from dictConfig") ``` -------------------------------- ### Configuration with YAML Source: https://context7.com/borntyping/python-colorlog/llms.txt Configure colorlog using YAML configuration with PyYAML. This method offers a more structured and readable way to define logging settings. ```yaml # logging.yaml version: 1 formatters: colorlog: (): 'colorlog.ColoredFormatter' format: '%(log_color)s%(asctime)s - %(name)-11s - %(levelname)-8s - %(message)s' log_colors: DEBUG: cyan INFO: green WARNING: yellow ERROR: red CRITICAL: bold_red handlers: console: class: logging.StreamHandler level: DEBUG formatter: colorlog stream: ext://sys.stdout loggers: '': level: DEBUG handlers: [console] application: level: INFO handlers: [console] propagate: no ``` -------------------------------- ### Configuration with fileConfig (INI file) Source: https://context7.com/borntyping/python-colorlog/llms.txt Configure colorlog using an INI configuration file. This is useful for separating logging configuration from application code. ```ini # logging.ini [loggers] keys=root [logger_root] handlers=stream level=DEBUG [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=%H:%M:%S [handlers] keys=stream [handler_stream] class=StreamHandler formatter=color args=() ``` -------------------------------- ### Loading Configuration from INI file Source: https://context7.com/borntyping/python-colorlog/llms.txt Load logging configuration from an INI file using logging.config.fileConfig. This allows externalizing logging settings. ```python import logging import logging.config logging.config.fileConfig("logging.ini") logger = logging.getLogger("example") logger.debug("Configured via INI file") logger.info("Colors defined in formatter_color section") ``` -------------------------------- ### Configuring ColoredFormatter with dictConfig Source: https://github.com/borntyping/python-colorlog/blob/main/README.md Sets up a 'colored' formatter using Python's logging.config.dictConfig. This formatter applies blue color to the message. ```python logging.config.dictConfig({ 'formatters': { 'colored': { '()': 'colorlog.ColoredFormatter', 'format': '%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s' } } }) ``` -------------------------------- ### Print All Available Escape Codes Source: https://context7.com/borntyping/python-colorlog/llms.txt Iterates through and prints all available escape codes provided by the colorlog library. Ensure 'escape_codes' is imported. ```python import colorlog from colorlog import escape_codes for key, value in colorlog.escape_codes.escape_codes.items(): print(f"{value}{key}{escape_codes['reset']}") ``` -------------------------------- ### Basic ColoredFormatter Usage Source: https://context7.com/borntyping/python-colorlog/llms.txt Demonstrates how to use ColoredFormatter to add color to log messages based on log level. Customize colors for each level and attach to a logger. ```python import logging from colorlog import ColoredFormatter # Create a colored formatter with custom colors per log level formatter = ColoredFormatter( fmt="%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s", datefmt=None, reset=True, log_colors={ "DEBUG": "cyan", "INFO": "green", "WARNING": "yellow", "ERROR": "red", "CRITICAL": "red,bg_white", }, secondary_log_colors={}, style="%" ) # Attach to a handler and logger handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger("example") logger.addHandler(handler) logger.setLevel(logging.DEBUG) # Log messages with colors logger.debug("a debug message") # Cyan level, blue message logger.info("an info message") # Green level, blue message logger.warning("a warning message") # Yellow level, blue message logger.error("an error message") # Red level, blue message logger.critical("a critical message") # Red on white level, blue message ``` -------------------------------- ### Custom Log Levels with Colors Source: https://context7.com/borntyping/python-colorlog/llms.txt Add custom log levels with their own colors to the colorlog formatter. This allows for more specific logging categories. ```python import logging from colorlog import ColoredFormatter TRACE = 5 logging.addLevelName(TRACE, "TRACE") formatter = ColoredFormatter( fmt="%(log_color)s%(levelname)-8s%(reset)s %(message)s", log_colors={ "TRACE": "purple", "DEBUG": "cyan", "INFO": "green", "WARNING": "yellow", "ERROR": "red", "CRITICAL": "bold_red", } ) handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger("example") logger.addHandler(handler) logger.setLevel(TRACE) logger.log(TRACE, "A trace message with purple color") logger.debug("Debug message") logger.info("Info message") ``` -------------------------------- ### ColoredFormatter with Secondary Log Colors Source: https://context7.com/borntyping/python-colorlog/llms.txt Configure multiple color attributes for different parts of the log message using secondary log colors. Each secondary color creates a new format variable. ```python import logging from colorlog import ColoredFormatter # Create formatter with secondary colors for different parts of the message formatter = ColoredFormatter( fmt="%(log_color)s%(levelname)-8s%(reset)s %(name_log_color)s[%(name)s]%(reset)s %(message_log_color)s%(message)s", log_colors={ "DEBUG": "white", "INFO": "green", "WARNING": "yellow", "ERROR": "red", "CRITICAL": "bold_red", }, secondary_log_colors={ "name": { "DEBUG": "blue", "INFO": "blue", "WARNING": "blue", "ERROR": "bold_blue", "CRITICAL": "bold_blue", }, "message": { "ERROR": "red", "CRITICAL": "bold_red", } } ) handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger("myapp") logger.addHandler(handler) logger.setLevel(logging.DEBUG) # Level name colored by log_colors, name colored by name_log_color, # message colored by message_log_color (only for ERROR/CRITICAL) logger.info("Normal message") # Green level, blue name, no message color logger.error("Error with red message") # Red level, bold blue name, red message ``` -------------------------------- ### Using secondary_log_colors in ColoredFormatter Source: https://github.com/borntyping/python-colorlog/blob/main/README.md Highlights the log level name using default colors and the message in red for ERROR and CRITICAL levels. Requires importing ColoredFormatter. ```python 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' } } ) ``` -------------------------------- ### Percent Style Formatting Source: https://context7.com/borntyping/python-colorlog/llms.txt Configures a ColoredFormatter using the percent style for log message formatting. This is the default style for Python's logging module. ```python import logging from colorlog import ColoredFormatter formatter_percent = ColoredFormatter( fmt="%(log_color)s%(levelname)s%(reset)s:%(name)s:%(message)s", style="%" ) ``` -------------------------------- ### Template Style Formatting Source: https://context7.com/borntyping/python-colorlog/llms.txt Configures a ColoredFormatter using the template style for log message formatting. This style uses dollar signs for placeholders, e.g., '${levelname}'. ```python import logging from colorlog import ColoredFormatter formatter_template = ColoredFormatter( fmt="${log_color}${levelname}${reset}:${name}:${message}", style="$" ) ``` -------------------------------- ### Configuring ColoredFormatter with fileConfig Source: https://github.com/borntyping/python-colorlog/blob/main/README.md Defines a formatter named 'color' using an INI-style configuration for fileConfig. This formatter includes background blue for the logger name. ```ini [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 from fileConfig datefmt=%m-%d %H:%M:%S ``` -------------------------------- ### Accessing Available Color Codes Source: https://context7.com/borntyping/python-colorlog/llms.txt Access and use ANSI escape codes directly from colorlog.escape_codes for custom styling. This provides a way to use raw color codes if needed. ```python import colorlog.escape_codes escape_codes = colorlog.escape_codes.escape_codes # Basic colors (foreground) # black, red, green, yellow, blue, purple, cyan, white # Light/bright colors # light_black, light_red, light_green, light_yellow, # light_blue, light_purple, light_cyan, light_white # Prefixed variants # fg_red, fg_bold_red, fg_thin_red (foreground) ``` -------------------------------- ### LevelFormatter Usage Source: https://context7.com/borntyping/python-colorlog/llms.txt Utilize LevelFormatter to apply different format strings for each log level, enabling distinct output formats based on severity. Customize colors for each level. ```python import logging import colorlog # Create a level formatter with different formats per level formatter = colorlog.LevelFormatter( fmt={ "DEBUG": "% (log_color)s% (message)s (%(module)s:%(lineno)d)", "INFO": "% (log_color)s% (message)s", "WARNING": "% (log_color)sWRN: % (message)s (%(module)s:%(lineno)d)", "ERROR": "% (log_color)sERR: % (message)s (%(module)s:%(lineno)d)", "CRITICAL": "% (log_color)sCRT: % (message)s (%(module)s:%(lineno)d)", }, log_colors={ "DEBUG": "cyan", "INFO": "green", "WARNING": "yellow", "ERROR": "red", "CRITICAL": "bold_red", } ) handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger("example") logger.addHandler(handler) logger.setLevel(logging.DEBUG) # Each level has its own format logger.debug("Debug with location info") # Shows module:lineno logger.info("Clean info message") # Just the message logger.error("Error with context") # Prefixed with ERR: ``` -------------------------------- ### Brace Style Formatting Source: https://context7.com/borntyping/python-colorlog/llms.txt Configures a ColoredFormatter using the brace style for log message formatting. This style uses curly braces for placeholders, e.g., '{levelname}'. ```python import logging from colorlog import ColoredFormatter formatter_brace = ColoredFormatter( fmt="{log_color}{levelname}{reset}:{name}:{message}", style="{" ) # Example with brace style handler = logging.StreamHandler() handler.setFormatter(formatter_brace) logger = logging.getLogger("styles") logger.addHandler(handler) logger.setLevel(logging.DEBUG) logger.info("Using brace-style formatting") ``` -------------------------------- ### TTY-Aware Colored Formatter Source: https://context7.com/borntyping/python-colorlog/llms.txt Configures a ColoredFormatter that automatically detects terminal capabilities (TTY) to enable or disable color output. Colors are disabled on non-TTY streams by default. The stream can be explicitly passed to the formatter. ```python import logging import sys from colorlog import ColoredFormatter formatter = ColoredFormatter( fmt="%(log_color)s%(levelname)s%(reset)s: %(message)s", stream=sys.stderr # Pass stream to enable TTY detection ) formatter_forced = ColoredFormatter( fmt="%(log_color)s%(levelname)s%(reset)s: %(message)s", force_color=True # Always output colors ) formatter_no_color = ColoredFormatter( fmt="%(log_color)s%(levelname)s%(reset)s: %(message)s", no_color=True # Never output colors ) # Environment variables also control behavior: # FORCE_COLOR - forces color output (like force_color=True) # NO_COLOR - disables color output (like no_color=True) handler = logging.StreamHandler(sys.stderr) handler.setFormatter(formatter) logger = logging.getLogger("tty_example") logger.addHandler(handler) logger.setLevel(logging.DEBUG) logger.info("Colored if stderr is a TTY, plain otherwise") ``` -------------------------------- ### Parse Multiple Colors from a String Source: https://context7.com/borntyping/python-colorlog/llms.txt Parses a string containing multiple color and style definitions to apply them to subsequent text. The 'parse_colors' function is used for this purpose. ```python import colorlog from colorlog import escape_codes color_sequence = colorlog.escape_codes.parse_colors("bold,red,bg_white") print(f"{color_sequence}Bold red text on white background{escape_codes['reset']}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.