### Install coloredlogs for basic logging Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Demonstrates how to install coloredlogs and set up basic logging. It imports the necessary libraries, calls the install function to configure logging with a specified level, and then creates a logger to output an informational message. This is analogous to Python's built-in logging.basicConfig(). ```python >>> import coloredlogs, logging >>> coloredlogs.install(level='DEBUG') >>> logger = logging.getLogger('some.module.name') >>> logger.info("this is an informational message") 2015-10-22 19:13:52 peter-macbook some.module.name[28036] INFO this is an informational message ``` -------------------------------- ### Install and Configure Colored Logging in Python Source: https://context7.com/xolox/python-coloredlogs/llms.txt Demonstrates how to use the coloredlogs.install() function to enable colored output for the root or specific loggers. It covers basic setup, custom formatting, style definitions for levels and fields, and system logging integration. ```python import coloredlogs import logging # Basic installation - enables colored logging at DEBUG level coloredlogs.install(level='DEBUG') # Create a logger for your module logger = logging.getLogger(__name__) # Install with a specific logger (only this logger's messages are colored) coloredlogs.install(level='DEBUG', logger=logger) # Customize the log format coloredlogs.install( level='INFO', fmt='%(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) # Enable milliseconds in timestamps coloredlogs.install(level='DEBUG', milliseconds=True) # Custom field and level styles (colors and text formatting) coloredlogs.install( level='DEBUG', level_styles={ 'debug': {'color': 'green'}, 'info': {}, 'warning': {'color': 'yellow'}, 'error': {'color': 'red'}, 'critical': {'color': 'red', 'bold': True}, }, field_styles={ 'asctime': {'color': 'green'}, 'hostname': {'color': 'magenta'}, 'levelname': {'color': 'black', 'bold': True}, 'name': {'color': 'blue'}, 'programname': {'color': 'cyan'}, 'username': {'color': 'yellow'}, } ) # Using format style (Python 3.2+) coloredlogs.install(level='DEBUG', fmt='{levelname}:{name}:{message}', style='{') # Enable system logging alongside terminal logging coloredlogs.install(level='DEBUG', syslog=True) # Logging 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") ``` -------------------------------- ### Basic coloredlogs Installation and Usage Source: https://context7.com/xolox/python-coloredlogs/llms.txt This Python code snippet shows the basic usage of the coloredlogs library. It imports the necessary modules, calls coloredlogs.install() to set up colored logging, and then retrieves a logger instance. A debug message is logged, demonstrating that the installation respects environment variables like COLOREDLOGS_LOG_LEVEL. ```python import coloredlogs import logging # Environment variables are automatically used when install() is called coloredlogs.install() logger = logging.getLogger(__name__) logger.debug("This respects COLOREDLOGS_LOG_LEVEL environment variable") ``` -------------------------------- ### coloredlogs.auto_install() Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Automatically calls install() when the $COLOREDLOGS_AUTO_INSTALL environment variable is set. ```APIDOC ## coloredlogs.auto_install() ### Description Automatically calls [`install()`](#coloredlogs.install) when `$COLOREDLOGS_AUTO_INSTALL` is set. This function uses [`coerce_boolean()`](https://humanfriendly.readthedocs.io/en/latest/api.html#humanfriendly.coerce_boolean) to check whether the value of `$COLOREDLOGS_AUTO_INSTALL` should be considered `True`. ### Behavior When the environment variable `$COLOREDLOGS_AUTO_INSTALL` is set and its value is interpreted as true, the `coloredlogs` module is imported and `auto_install()` is called. This is facilitated by a path configuration file in the `coloredlogs` package. ``` -------------------------------- ### Install coloredlogs and dependencies Source: https://github.com/xolox/python-coloredlogs/blob/master/README.rst Commands to install the coloredlogs package and the optional colorama dependency for improved Windows terminal compatibility. ```console pip install coloredlogs pip install colorama ``` -------------------------------- ### Manage logging verbosity and levels Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Provides examples for adjusting the root handler's verbosity and setting specific log levels programmatically. ```python import coloredlogs # Increase or decrease verbosity coloredlogs.increase_verbosity() coloredlogs.decrease_verbosity() # Set a specific log level coloredlogs.set_level('DEBUG') # Check current level current_level = coloredlogs.get_level() ``` -------------------------------- ### Manual Configuration with ColoredFormatter Source: https://context7.com/xolox/python-coloredlogs/llms.txt Shows how to instantiate the ColoredFormatter class directly for fine-grained control over logging handlers. This is useful when you need to attach colored logging to specific handlers rather than using the global install function. ```python import logging import coloredlogs # Create a ColoredFormatter instance formatter = coloredlogs.ColoredFormatter( fmt='%(asctime)s %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S', level_styles={ 'debug': {'color': 'green'}, 'info': {'color': 'white'}, 'warning': {'color': 'yellow'}, 'error': {'color': 'red'}, 'critical': {'color': 'red', 'bold': True, 'background': 'white'}, }, field_styles={ 'asctime': {'color': 'cyan'}, 'levelname': {'bold': True}, 'name': {'color': 'blue'}, } ) # Create and configure a handler manually handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) # Add the handler to a logger logger = logging.getLogger('my_app') logger.addHandler(handler) logger.setLevel(logging.DEBUG) logger.info("Manually configured colored logging!") ``` -------------------------------- ### Parse and apply custom logging styles Source: https://context7.com/xolox/python-coloredlogs/llms.txt Shows how to parse encoded style strings into configuration dictionaries and apply them to the coloredlogs installation. Supports colors, background colors, and text attributes like bold. ```python import coloredlogs encoded = 'debug=green;warning=yellow;error=red;critical=red,bold' styles = coloredlogs.parse_encoded_styles(encoded) coloredlogs.install( level='DEBUG', level_styles=coloredlogs.parse_encoded_styles('debug=green;error=red,bold') ) ``` -------------------------------- ### Programmatic Verbosity Control in coloredlogs Source: https://context7.com/xolox/python-coloredlogs/llms.txt This Python code illustrates how to programmatically control logging verbosity using coloredlogs. It covers initializing logging, getting the current log level, setting a specific level, increasing and decreasing verbosity, and checking if logging is verbose. It also includes an example of integrating verbosity control with argparse for command-line tools. ```python import coloredlogs import logging # Initialize colored logging coloredlogs.install(level='INFO') logger = logging.getLogger(__name__) # Get the current log level current_level = coloredlogs.get_level() print(f"Current level: {current_level}") # Output: Current level: 20 # Set a specific log level coloredlogs.set_level('DEBUG') logger.debug("Now visible after setting level to DEBUG") # Increase verbosity (lower log level number = more verbose) coloredlogs.increase_verbosity() logger.debug("Even more verbose logging") # Decrease verbosity (higher log level number = less verbose) coloredlogs.decrease_verbosity() # Check if logging is verbose (level < INFO) if coloredlogs.is_verbose(): logger.debug("Running in verbose mode") # Example CLI tool with verbosity flag import argparse parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbose', action='count', default=0) args = parser.parse_args() coloredlogs.install(level='WARNING') for _ in range(args.verbose): coloredlogs.increase_verbosity() logger.warning("Always visible") logger.info("Visible with -v") logger.debug("Visible with -vv") ``` -------------------------------- ### Configure Colored Logs via Environment Variables Source: https://context7.com/xolox/python-coloredlogs/llms.txt Provides examples of configuring coloredlogs behavior using shell environment variables. This approach allows modifying logging output without changing the application source code. ```bash # Set the default log level export COLOREDLOGS_LOG_LEVEL=DEBUG # Customize the log format export COLOREDLOGS_LOG_FORMAT='%(asctime)s %(levelname)s %(message)s' # Customize the date/time format export COLOREDLOGS_DATE_FORMAT='%Y-%m-%d %H:%M:%S' # Customize level styles (format: level=style;level=style) export COLOREDLOGS_LEVEL_STYLES='debug=green;warning=yellow;error=red;critical=red,bold' # Customize field styles export COLOREDLOGS_FIELD_STYLES='asctime=green;hostname=magenta;levelname=black,bold;name=blue' # Auto-install coloredlogs when Python starts export COLOREDLOGS_AUTO_INSTALL=true # Disable colors (respects the NO_COLOR standard) export NO_COLOR=1 ``` -------------------------------- ### Add Hostname to Log Records with coloredlogs.HostNameFilter Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md This filter enables the %(hostname)s field in log format strings by adding the system's hostname to each LogRecord. It can be installed manually by adding the filter to a handler and setting a formatter, or automatically via coloredlogs.install(). ```python import coloredlogs, logging handler = logging.StreamHandler() handler.addFilter(coloredlogs.HostNameFilter()) handler.setFormatter(logging.Formatter('[%(hostname)s] %(message)s')) logger = logging.getLogger() logger.addHandler(handler) logger.setLevel(logging.INFO) logger.info("Does it work?") ``` -------------------------------- ### Convert ANSI to HTML with coloredlogs.converter Source: https://context7.com/xolox/python-coloredlogs/llms.txt This Python code snippet demonstrates how to convert terminal output containing ANSI escape sequences into HTML using the `coloredlogs.converter` module. It shows the `convert` function for direct conversion and mentions the `capture` and `html_encode` functions for more advanced use cases, including an example of converting colored text to HTML spans. ```python from coloredlogs.converter import convert, capture, html_encode # Convert text with ANSI codes to HTML ansi_text = "\x1b[32mGreen text\x1b[0m and \x1b[31mred text\x1b[0m" html_output = convert(ansi_text) print(html_output) # Output: Green text and red text # Convert without wrapping in tags html_output = convert(ansi_text, code=False) ``` -------------------------------- ### Normalize Name with NameNormalizer (Python) Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Normalizes a given string by converting it to lowercase and resolving level name aliases to their canonical form. This is useful for standardizing log level names. It relies on the 'humanfriendly' library for formatting the output table in the example. ```python from coloredlogs import NameNormalizer from humanfriendly import format_table nn = NameNormalizer() sample_names = ['DEBUG', 'INFO', 'WARN', 'WARNING', 'ERROR', 'FATAL', 'CRITICAL'] print(format_table([(n, nn.normalize_name(n)) for n in sample_names])) ``` -------------------------------- ### Add Program Name to Log Records with coloredlogs.ProgramNameFilter Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md This filter adds the %(programname)s field to log records, making the name of the currently running program available in log messages. It can be installed manually, similar to HostNameFilter, or through convenience methods provided by the library. ```python import coloredlogs, logging # Example of manual installation (refer to HostNameFilter for full context) handler = logging.StreamHandler() # Assuming ProgramNameFilter is instantiated and added to handler # logger.addHandler(handler) # logger.info("Log message with program name") ``` -------------------------------- ### coloredlogs.install() Configuration Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md This section details the parameters available for configuring the coloredlogs.install() function to customize terminal logging output. ```APIDOC ## coloredlogs.install() ### Description Enable colored terminal output for Python’s `logging` module. ### Method Python Function Call ### Endpoint N/A (Python function) ### Parameters #### Function Arguments - **level** (int or str) - Optional - The default logging level. - **logger** (logging.Logger) - Optional - The logger to which the stream handler should be attached (defaults to the root logger). - **fmt** (str) - Optional - Set the logging format string. - **datefmt** (str) - Optional - Set the date/time format string. - **style** (str) - Optional - One of the characters '%', '{' or '$' (defaults to `DEFAULT_FORMAT_STYLE`). - **milliseconds** (bool) - Optional - `True` to show milliseconds, `False` to hide them (defaults to `False`). - **level_styles** (dict) - Optional - A dictionary with custom level styles. - **field_styles** (dict) - Optional - A dictionary with custom field styles. - **stream** (file-like object) - Optional - The stream where log messages should be written to (defaults to `None`, using `StandardErrorHandler`). - **isatty** (bool) - Optional - `True` to use `ColoredFormatter`, `False` to use a normal `Formatter` (defaults to auto-detection). - **reconfigure** (bool) - Optional - If `True` (default), multiple calls override previous configurations. - **use_chroot** - Optional - Refer to `HostNameFilter`. - **programname** - Optional - Refer to `ProgramNameFilter`. - **username** - Optional - Refer to `UserNameFilter`. - **syslog** (bool or int or str) - Optional - If `True`, calls `enable_system_logging()` without arguments. Can also be a logging level. ### Request Example ```python import coloredlogs import logging coloredlogs.install(level='INFO', fmt='%(asctime)s - %(levelname)s - %(message)s') logging.info('This is an informational message.') ``` ### Response #### Success Response This function modifies the logging configuration in place and does not return a specific value. #### Response Example N/A ``` -------------------------------- ### Initialize and use coloredlogs Source: https://github.com/xolox/python-coloredlogs/blob/master/README.rst Demonstrates how to initialize coloredlogs to format terminal output and log messages at various severity levels. ```python import coloredlogs, logging # Create a logger object. logger = logging.getLogger(__name__) # Install coloredlogs on the logger coloredlogs.install(level='DEBUG', logger=logger) # Log messages 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") ``` -------------------------------- ### Get Value from Normalized Dictionary (Python) Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Retrieves a value from a dictionary whose keys have already been normalized using normalize_keys. It takes a normalized dictionary and a name (key) to look up, normalizing the provided name before searching. ```python from coloredlogs import NameNormalizer nn = NameNormalizer() normalized_dict = {'debug': 1, 'warning': 2} value = nn.get(normalized_dict, 'Debug') print(value) ``` -------------------------------- ### connect_to_syslog Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Creates a SysLogHandler for connecting to the system logging daemon. ```APIDOC ## POST /xolox/python-coloredlogs/syslog/connect_to_syslog ### Description Creates a `SysLogHandler` for connecting to the system logging daemon. ### Method POST ### Endpoint /xolox/python-coloredlogs/syslog/connect_to_syslog ### Parameters #### Query Parameters - **address** (string or tuple) - Optional - The device file or network address of the system logging daemon. - **facility** (int) - Optional - Refer to `logging.handlers.SysLogHandler` facility codes. Defaults to `LOG_USER`. - **level** (int) - Optional - The logging level for the `SysLogHandler`. ### Response #### Success Response (200) - **handler** (`logging.handlers.SysLogHandler` or `None`) - A `SysLogHandler` object or `None` if the system logging daemon is unavailable. ### Notes - The process tries `SOCK_RAW` (preferred) and then `SOCK_STREAM` (TCP) socket types. - Supports longer messages with `SOCK_STREAM` compared to the default UDP. ``` -------------------------------- ### Command Line Interface utilities Source: https://context7.com/xolox/python-coloredlogs/llms.txt Demonstrates the usage of the coloredlogs CLI tool for demonstrating log styles and converting command output to HTML directly from the shell. ```bash coloredlogs --demo coloredlogs --to-html ls --color=always COLOREDLOGS_DEMO_DELAY=0.5 coloredlogs --demo ``` -------------------------------- ### Enable Syslog Support with COLOREDLOGS_SYSLOG Source: https://context7.com/xolox/python-coloredlogs/llms.txt This snippet demonstrates how to enable syslog support for coloredlogs by setting the COLOREDLOGS_SYSLOG environment variable to 'true'. It then shows how coloredlogs.install() automatically picks up this setting and configures logging accordingly, including a debug message that respects the COLOREDLOGS_LOG_LEVEL environment variable. ```shell export COLOREDLOGS_SYSLOG=true ``` -------------------------------- ### Implement dynamic stderr logging with StandardErrorHandler Source: https://context7.com/xolox/python-coloredlogs/llms.txt Demonstrates how to manually instantiate and configure the StandardErrorHandler. This allows log messages to follow changes to sys.stderr dynamically, which is useful for applications that redirect output streams at runtime. ```python import logging import sys import coloredlogs # Manual usage for advanced scenarios handler = coloredlogs.StandardErrorHandler() handler.setLevel(logging.DEBUG) handler.setFormatter(coloredlogs.ColoredFormatter()) logger = logging.getLogger('dynamic_stderr') logger.addHandler(handler) logger.setLevel(logging.DEBUG) # This works even if sys.stderr is replaced later original_stderr = sys.stderr sys.stderr = open('/tmp/log_output.txt', 'w') logger.info("This goes to the new stderr") sys.stderr.close() sys.stderr = original_stderr logger.info("Back to original stderr") ``` -------------------------------- ### Configure date and time format via environment variables Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Shows how to customize the timestamp display in logs by setting COLOREDLOGS_DATE_FORMAT. This allows users to simplify or reformat the date/time string appended to log entries. ```console export COLOREDLOGS_LOG_FORMAT='%(asctime)s - %(message)s' export COLOREDLOGS_DATE_FORMAT='%H:%M:%S' coloredlogs --demo ``` -------------------------------- ### Configure and run coloredlogs demo via CLI Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/examples/custom-log-format.txt Sets the COLOREDLOGS_LOG_FORMAT environment variable to define a custom log format and executes the coloredlogs demo command. This demonstrates how the library formats logs with different severity levels in the terminal. ```bash export COLOREDLOGS_LOG_FORMAT='[%(hostname)s] %(asctime)s %(message)s' coloredlogs --demo ``` -------------------------------- ### Configure millisecond precision in logs Source: https://github.com/xolox/python-coloredlogs/blob/master/README.rst Shows how to enable millisecond precision in log timestamps either by passing a boolean argument or by defining a custom format string. ```python # 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') ``` -------------------------------- ### Redirecting Logs to System Log (Syslog) Source: https://context7.com/xolox/python-coloredlogs/llms.txt This Python code demonstrates how to redirect log messages to the system log (syslog) using coloredlogs. It shows the use of `enable_system_logging` for direct syslog redirection and its use as a context manager. It also illustrates combining terminal and system logging by passing the `syslog` argument to `coloredlogs.install()`. ```python import logging from coloredlogs.syslog import enable_system_logging, SystemLogging logger = logging.getLogger(__name__) # Enable system logging (messages go to /var/log/syslog on Linux) handler = enable_system_logging( programname='my_app', level='INFO', fmt='%(programname)s[%(process)d]: %(levelname)s %(message)s' ) if handler: logger.info("This message goes to system log") else: logger.warning("System logging not available on this platform") # Use as a context manager for temporary system logging with SystemLogging(level='DEBUG') as handler: if handler: logger.debug("This goes to syslog") # System logging is automatically disabled after the context # Combine terminal and system logging import coloredlogs coloredlogs.install(level='DEBUG', syslog='INFO') # syslog at INFO level logger.debug("Terminal only") logger.info("Both terminal and syslog") ``` -------------------------------- ### enable_system_logging Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Redirects logging messages to the system log (e.g., /var/log/syslog). ```APIDOC ## POST /xolox/python-coloredlogs/syslog/enable_system_logging ### Description Redirects `logging` messages to the system log (e.g. `/var/log/syslog`). ### Method POST ### Endpoint /xolox/python-coloredlogs/syslog/enable_system_logging ### Parameters #### Query Parameters - **programname** (string) - Optional - The program name to embed in log messages. - **fmt** (string) - Optional - The log format for system log messages. - **logger** (logging.Logger) - Optional - The logger to which the `SysLogHandler` should be connected. - **level** (int) - Optional - The logging level for the `SysLogHandler`. - **reconfigure** (boolean) - Optional - If `True` (the default), multiple calls will override previous configurations. #### Request Body - **kw** (object) - Keyword arguments passed to `connect_to_syslog()`. ### Response #### Success Response (200) - **handler** (`logging.handlers.SysLogHandler` or `None`) - A `SysLogHandler` object or `None` if the connection fails or an existing handler is returned when `reconfigure` is `False`. ### Notes - As of release 15.0, this function uses `is_syslog_supported()` to check for system logging support before enabling. - If the logger's effective level is too restrictive, it is relaxed. ``` -------------------------------- ### Configure custom colors and text styles Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Explains how to apply advanced styling to log levels using COLOREDLOGS_LEVEL_STYLES. This supports 256-color codes, bold text, and background colors for specific log levels. ```console export COLOREDLOGS_LOG_FORMAT='%(asctime)s - %(message)s' export COLOREDLOGS_DATE_FORMAT='%H:%M:%S' export COLOREDLOGS_FIELD_STYLES='' export COLOREDLOGS_LEVEL_STYLES='spam=22;debug=28;verbose=34;notice=220;warning=202;success=118,bold;error=124;critical=background=red' coloredlogs --demo ``` -------------------------------- ### SystemLogging Context Manager Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md The SystemLogging class provides a context manager for enabling and disabling system logging. ```APIDOC ## SystemLogging Class ### Description Provides a context manager for enabling and disabling system logging. ### Methods - `__init__(*args, **kw)`: Initialize a `SystemLogging` object. Accepts positional and keyword arguments for `enable_system_logging()`. - `__enter__()`: Enable system logging when entering the context. - `__exit__(exc_type=None, exc_value=None, traceback=None)`: Disable system logging when leaving the context. Logs a warning with traceback if an exception is being handled. ### Notes If an exception is being handled when exiting the context, a warning message including the traceback is logged before system logging is disabled. ``` -------------------------------- ### Convert ANSI terminal output to HTML Source: https://context7.com/xolox/python-coloredlogs/llms.txt Demonstrates how to capture command output containing ANSI color sequences and convert it into HTML format. This is useful for generating web-ready logs from terminal commands. ```python captured = capture(['ls', '--color=always', '/tmp']) html_output = convert(captured) # HTML encode plain text safe_text = html_encode('') def get_colored_command_html(command): output = capture(command) return convert(output) html = get_colored_command_html(['git', 'status']) with open('git_status.html', 'w') as f: f.write(f'{html}') ``` -------------------------------- ### System Identification Helpers Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Functions to retrieve system-level information for log metadata. ```APIDOC ## FUNCTION coloredlogs.find_hostname ### Description Determines the hostname to include in log messages, checking chroot environments before falling back to socket.gethostname(). ### Parameters #### Query Parameters - **use_chroot** (boolean) - Optional - Whether to use the chroot name if available. Defaults to True. ### Response - **hostname** (string) - The identified host name. --- ## FUNCTION coloredlogs.find_username ### Description Finds the current username for log attribution, using the pwd module on UNIX or getpass on Windows. ### Response - **username** (string) - The identified system username. ``` -------------------------------- ### Configure Cron Job for Colored Output Source: https://github.com/xolox/python-coloredlogs/blob/master/README.rst Demonstrates how to configure a crontab entry to use the coloredlogs utility to convert ANSI escape sequences into HTML for email notifications. ```bash MAILTO="your-email-address@here" CONTENT_TYPE="text/html" * * * * * root coloredlogs --to-html your-command ``` -------------------------------- ### Inspect logging levels in coloredlogs Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Demonstrates how to retrieve the currently defined logging levels and their corresponding integer values using the find_defined_levels function. ```python import coloredlogs # Retrieve defined logging levels levels = coloredlogs.find_defined_levels() print(levels) ``` -------------------------------- ### Discover and normalize logging levels Source: https://context7.com/xolox/python-coloredlogs/llms.txt Utilities for inspecting available logging levels, resolving aliases (e.g., FATAL to CRITICAL), and normalizing level names. Useful for integrating with third-party logging extensions. ```python import coloredlogs levels = coloredlogs.find_defined_levels() aliases = coloredlogs.find_level_aliases() normalizer = coloredlogs.NameNormalizer() print(normalizer.normalize_name('WARN')) level_num = coloredlogs.level_to_number('DEBUG') ``` -------------------------------- ### coloredlogs.syslog.is_syslog_supported() Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Determines whether system logging is supported on the current platform, considering environment variables and OS-specific behaviors. ```APIDOC ## coloredlogs.syslog.is_syslog_supported() ### Description Determine whether system logging is supported. ### Method GET (conceptual, as this is a function call) ### Endpoint N/A (Python function) ### Parameters None ### Request Example N/A ### Response #### Success Response - **return_value** (boolean) - True if system logging is supported, False otherwise. #### Response Example ``` True ``` OR ``` False ``` ``` -------------------------------- ### Enable Millisecond Precision in Timestamps Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/readme.md Demonstrates how to include milliseconds in log timestamps using coloredlogs. This can be achieved by passing `milliseconds=True` to `coloredlogs.install()` or by customizing the log format string to include `%(msecs)03d` or `%f`. ```python import coloredlogs coloredlogs.install(milliseconds=True) ``` ```python import coloredlogs coloredlogs.install(fmt='%(asctime)s,%(msecs)03d %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s') ``` ```python import coloredlogs coloredlogs.install(fmt='%(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S.%f') ``` -------------------------------- ### coloredlogs.FORMAT_STYLE_PATTERNS Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md A dictionary mapping style characters to regular expression patterns for parsing logging format strings. ```APIDOC ## coloredlogs.FORMAT_STYLE_PATTERNS ### Description A dictionary that maps the style characters `%`, `{` and `$` to strings containing regular expression patterns that can be used to parse format strings in the corresponding style. ### Style Mappings - **`%`**: Regular expression for percent conversion specifiers (e.g., `%(levelname)s:%(name)s:%(message)s`). - **`{`**: Regular expression for replacement fields (e.g., `{levelname}:{name}:{message}`). - **`$`**: Regular expression for substitution placeholders (e.g., `$levelname:$name:$message`). ### Usage These regular expressions are used by `FormatStringParser` to introspect and manipulate logging format strings. ``` -------------------------------- ### Capture External Command Output (Python) Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Captures the output of an external command, emulating an interactive terminal session using the 'script' utility. This is useful for capturing command output that includes ANSI escape sequences. It allows specifying the output encoding. ```python from coloredlogs.converter import capture command = ['ls', '-l'] output = capture(command) print(output) ``` -------------------------------- ### Custom Log Format Fields in Coloredlogs Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/readme.md Illustrates how to use custom fields like hostname, program name, and username in log messages. When these fields are detected in the format string, coloredlogs automatically registers the necessary filters to populate them. ```python import coloredlogs coloredlogs.install(fmt='%(asctime)s %(hostname)s %(programname)s %(username)s: %(levelname)s %(message)s') ``` -------------------------------- ### coloredlogs.syslog.find_syslog_address() Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Finds the most suitable destination for system log messages, returning a pathname or an address/port tuple. ```APIDOC ## coloredlogs.syslog.find_syslog_address() ### Description Find the most suitable destination for system log messages. ### Method GET (conceptual, as this is a function call) ### Endpoint N/A (Python function) ### Parameters None ### Request Example N/A ### Response #### Success Response - **return_value** (string or tuple) - The pathname of a log device or an address/port tuple. #### Response Example ``` '/dev/log' ``` OR ``` ('localhost', 514) ``` ``` -------------------------------- ### Validate logging format styles Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Validates if a provided logging format style is supported by the current Python environment. ```python import coloredlogs try: style = coloredlogs.check_style('%') print(f"Valid style: {style}") except ValueError as e: print(f"Invalid style: {e}") ``` -------------------------------- ### coloredlogs.replace_handler Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Utility to manage and replace logging handlers within a logger instance. ```APIDOC ## FUNCTION coloredlogs.replace_handler ### Description Prepares to replace an existing logging handler with a new configuration. ### Parameters - **logger** (object) - Required - The logger instance to inspect. - **match_handler** (object) - Required - The handler to search for. - **reconfigure** (boolean) - Required - True to replace the handler, False otherwise. ### Response #### Success Response (200) - **result** (tuple) - A tuple containing the matched Handler object (or None) and the associated Logger object. ``` -------------------------------- ### Convert ANSI to HTML (Python) Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Converts text containing ANSI escape sequences into HTML. It can optionally wrap the output in a '' tag and allows specifying the tab size for expansion. This is useful for displaying terminal output in web pages. ```python from coloredlogs.converter import convert ansi_text = "\033[31mThis is red text\033[0m" html_output = convert(ansi_text) print(html_output) ``` -------------------------------- ### Replace Logging Handler in Coloredlogs Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Prepares to replace an existing logging handler within a logger. It takes the logger, a matching handler criteria, and a boolean to indicate whether to reconfigure. It returns the matched handler and the logger it was attached to, or None if no handler matched. ```python import logging from coloredlogs import replace_handler, find_handler logger = logging.getLogger('my_app') logger.setLevel(logging.INFO) # Assuming a handler exists that matches certain criteria # matched_handler, logger = replace_handler(logger, match_handler=lambda h: isinstance(h, logging.StreamHandler), reconfigure=True) # Example usage would involve finding a handler first, then potentially replacing it. # This snippet demonstrates the function signature and basic idea. ``` -------------------------------- ### Automate colored HTML emails in cron jobs Source: https://context7.com/xolox/python-coloredlogs/llms.txt Uses the ColoredCronMailer context manager to automatically capture and convert log output to HTML when running in a cron environment. It supports silencing output if no significant work is performed. ```python from coloredlogs.converter import ColoredCronMailer import coloredlogs import logging def main(): with ColoredCronMailer() as mailer: coloredlogs.install(level='DEBUG') logger = logging.getLogger(__name__) logger.info("Processing started...") logger.warning("Something needs attention") if no_work_to_do: mailer.silence() ``` -------------------------------- ### Find Level Aliases in Coloredlogs Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Retrieves a dictionary mapping short log level aliases to their canonical names. This function is useful for understanding how different log level abbreviations are interpreted by the library. It does not require any external dependencies beyond the coloredlogs library itself. ```python from coloredlogs import find_level_aliases print(find_level_aliases()) ``` -------------------------------- ### coloredlogs.syslog.match_syslog_handler(handler) Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Identifies if a given logging handler is an instance of SysLogHandler. ```APIDOC ## coloredlogs.syslog.match_syslog_handler(handler) ### Description Identify system logging handlers. ### Method GET (conceptual, as this is a function call) ### Endpoint N/A (Python function) ### Parameters #### Path Parameters - **handler** (logging.Handler) - The Handler class to check. ### Request Example N/A ### Response #### Success Response - **return_value** (boolean) - True if the handler is a SysLogHandler, False otherwise. #### Response Example ``` True ``` OR ``` False ``` ``` -------------------------------- ### Normalize Dictionary Keys (Python) Source: https://github.com/xolox/python-coloredlogs/blob/master/docs/api.md Normalizes the keys of a dictionary by applying the normalize_name function to each key. This ensures consistency when working with dictionary data, especially for log-related information. ```python from coloredlogs import NameNormalizer nn = NameNormalizer() my_dict = {'DEBUG': 1, 'WARNING': 2} normalized_dict = nn.normalize_keys(my_dict) print(normalized_dict) ```