API Reference¶
This section details the classes, methods, functions, and constants provided by the ascii_colors
library.
Core Class: ASCIIColors
¶
The central class managing global logging state and providing static methods for direct terminal printing.
- class ascii_colors.ASCIIColors[source]¶
Bases:
object
Provides static methods for colored/styled terminal output (direct printing) and manages the global state for the structured logging system.
Dual Functionality:
Direct Printing: Use methods like ASCIIColors.red(), ASCIIColors.bold(), ASCIIColors.print(), ASCIIColors.highlight() etc., to print directly to the console (sys.stdout by default) with ANSI styling. These methods bypass the logging system. They are simple utilities for immediate output.
Logging System Management: This class holds the central list of handlers (_handlers), the global logging level (_global_level), and provides methods (add_handler, set_log_level, etc.) to configure the logging system. The logging methods (ASCIIColors.debug(), info(), etc.) and the compatibility layer (getLogger, basicConfig) all interact with this global state.
Color and Style Constants: Numerous class attributes define ANSI escape codes for colors and styles (e.g., color_red, style_bold, color_bg_green). See the Usage documentation for a complete list.
Direct Print Methods (Bypass Logging System)
These methods print directly to the console (default sys.stdout).
- static print(text, color='\x1b[37m', style='', background='', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Prints text directly to a stream with specified color, style, and background.
This method bypasses the entire logging system (handlers, formatters, levels, context). It’s a direct wrapper around the built-in print.
- Parameters:
text (str) – The string to print.
color (str) – ANSI foreground color code (e.g., ASCIIColors.color_red). Defaults to color_white.
style (str) – ANSI style code(s) (e.g., ASCIIColors.style_bold). Multiple styles can be concatenated (e.g., style_bold + style_underline). Defaults to “”.
background (str) – ANSI background color code (e.g., ASCIIColors.color_bg_blue). Defaults to “”.
end (str) – String appended after the text. Defaults to newline (n).
flush (bool) – Whether to forcibly flush the stream. Defaults to False.
file (TextIO | IO[str]) – The stream to write to. Defaults to sys.stdout.
- Return type:
None
- static print_with_bg(text, color='\x1b[37m', background='', style='', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
[DEPRECATED] Helper to print with background; use ASCIIColors.print() with background parameter instead. Directly prints text with specified foreground color, background color, and style.
- static success(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in green color.
- static fail(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in red color.
- static black(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in black color.
- static red(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in red color.
- static green(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in green color.
- static yellow(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in yellow color.
- static blue(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in blue color.
- static magenta(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in magenta color.
- static cyan(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in cyan color.
- static white(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in white color.
- static orange(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in orange color (256-color approx).
- static bright_black(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright black (gray) color.
- static bright_red(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright red color.
- static bright_green(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright green color.
- static bright_yellow(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright yellow color.
- static bright_blue(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright blue color.
- static bright_magenta(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright magenta color.
- static bright_cyan(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright cyan color.
- static bright_white(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright white color.
- static bg_black(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a black background.
- static bg_red(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a red background.
- static bg_green(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a green background.
- static bg_yellow(text, color='\x1b[30m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a yellow background (default text: black).
- static bg_blue(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a blue background.
- static bg_magenta(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a magenta background.
- static bg_cyan(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a cyan background.
- static bg_white(text, color='\x1b[30m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a white background (default text: black).
- static bg_orange(text, color='\x1b[30m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with an orange background (256-color approx, default text: black).
- static bg_bright_black(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright black (gray) background.
- static bg_bright_red(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright red background.
- static bg_bright_green(text, color='\x1b[30m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright green background (default text: black).
- static bg_bright_yellow(text, color='\x1b[30m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright yellow background (default text: black).
- static bg_bright_blue(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright blue background.
- static bg_bright_magenta(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright magenta background.
- static bg_bright_cyan(text, color='\x1b[30m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright cyan background (default text: black).
- static bg_bright_white(text, color='\x1b[30m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright white background (default text: black).
- static bold(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bold style.
- static dim(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in dim style.
- static italic(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in italic style.
- static underline(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in underline style.
- static blink(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in blinking style.
- static reverse(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in reverse video style.
Directly prints text in hidden style.
- static strikethrough(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in strikethrough style.
- static multicolor(texts, colors, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints multiple text segments with corresponding colors on one line.
This method bypasses the logging system. Each text segment in texts is printed using the corresponding color code from colors. A single reset code is added at the very end.
- Parameters:
texts (List[str]) – A list of strings to print sequentially.
colors (List[str]) – A list of ANSI color/style codes, corresponding to texts. Must have the same length as texts.
end (str) – String appended after all segments. Defaults to newline (n).
flush (bool) – Whether to forcibly flush the stream. Defaults to False.
file (TextIO | IO[str]) – The stream to write to. Defaults to sys.stdout.
- Return type:
None
- static highlight(text, subtext, color='\x1b[37m', highlight_color='\x1b[33m', whole_line=False, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text, highlighting occurrences of subtext(s).
This method bypasses the logging system. It searches for subtext within text and applies highlight_color to the matches.
- Parameters:
text (str) – The main string to print.
subtext (str | List[str]) – The string or list of strings to highlight within text.
color (str) – The default ANSI color code for non-highlighted parts of text. Defaults to color_white.
highlight_color (str) – The ANSI color/style code to apply to matched subtext. Defaults to color_yellow. Can include styles/backgrounds.
whole_line (bool) – If True, highlight the entire line if any part of subtext is found in it. If False (default), only highlight the matched subtext itself.
end (str) – String appended after the text. Defaults to newline (n).
flush (bool) – Whether to forcibly flush the stream. Defaults to False.
file (TextIO | IO[str]) – The stream to write to. Defaults to sys.stdout.
- Return type:
None
- static activate(color_or_style, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Activates a specific ANSI color or style directly on the stream.
This method bypasses the logging system. It prints the given ANSI code without any text or reset code afterwards. Useful for setting a style that persists across multiple subsequent prints until reset() is called.
- static reset(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Resets all active ANSI colors and styles directly on the stream.
This method bypasses the logging system. It prints the color_reset code.
- static resetAll(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Alias for reset().
Console Utilities (Using Direct Printing)
- static execute_with_animation(pending_text, func, *args, color=None, **kwargs)[source]¶
Executes a function while displaying a console spinner animation.
This utility uses direct printing (ASCIIColors.print) to show and update the spinner animation on sys.stdout. It runs the provided func in a separate thread. Once the function completes (or raises an exception), the animation stops, a final status (success ✓ or failure ✗) is printed, and the function’s result is returned or its exception is re-raised.
Note: Log messages generated within the executed func will still go through the standard logging system and appear separately from the spinner line.
- Parameters:
pending_text (str) – The text message to display next to the spinner (e.g., “Processing…”).
func (Callable[[...], _T]) – The callable (function or method) to execute.
*args (Any) – Positional arguments to pass to func.
color (str | None) – Optional ANSI color code for the pending_text. Defaults to yellow.
**kwargs (Any) – Keyword arguments to pass to func.
- Returns:
The return value of the executed func.
- Raises:
Exception – Re-raises any exception raised by the executed func.
- Return type:
_T
Example
>>> result = ASCIIColors.execute_with_animation("Loading data...", time.sleep, 2) # Displays "Loading data... [spinner]" for 2 seconds, then success status.
Logging Methods (Use Logging System)
These methods create log records processed by configured handlers and formatters.
- classmethod debug(message, *args, **kwargs)[source]¶
Logs a message with level DEBUG using the configured logging system.
- classmethod info(message, *args, **kwargs)[source]¶
Logs a message with level INFO using the configured logging system.
- classmethod warning(message, *args, **kwargs)[source]¶
Logs a message with level WARNING using the configured logging system.
- classmethod error(message, *args, exc_info=None, **kwargs)[source]¶
Logs a message with level ERROR using the configured logging system.
- Parameters:
message (str) – The log message (can be a format string).
*args (Any) – Arguments for %-formatting of the message.
exc_info (bool | BaseException | Tuple[Type[BaseException] | None, BaseException | None, Any] | None) – Optional exception information to include (None, True, Exception, tuple).
**kwargs (Any) – Extra context data.
- Return type:
None
- classmethod critical(message, *args, **kwargs)[source]¶
Logs a message with level CRITICAL using the configured logging system.
Global Logging Configuration
Methods to manage the global logging state (handlers, level).
- classmethod set_log_level(level)[source]¶
Sets the global minimum log level for the entire logging system.
Messages with a severity lower than this level will be ignored and not processed by any handlers.
- Parameters:
level (LogLevel | int) – The minimum log level (LogLevel enum or int) to set globally.
- Return type:
None
- classmethod add_handler(handler)[source]¶
Adds a Handler instance to the global list of handlers.
All log records that pass the global level filter will be processed by this handler (subject to the handler’s own level filter).
- Parameters:
handler (Handler) – The Handler instance to add.
- Return type:
None
- classmethod remove_handler(handler)[source]¶
Removes a specific Handler instance from the global list.
- Parameters:
handler (Handler) – The Handler instance to remove. If the handler is not found, this method does nothing.
- Return type:
None
- classmethod clear_handlers()[source]¶
Removes all configured handlers from the global list.
Note: This does not automatically call the close() method on the removed handlers. If handlers manage resources (like files), they should be closed explicitly or via basicConfig(force=True).
- Return type:
None
Thread-Local Context Management
Methods to manage contextual information added to log records.
- classmethod set_context(**kwargs)[source]¶
Sets key-value pairs in the current thread’s logging context.
These context variables will be included in the log_record dictionary passed to formatters, allowing them to be included in log messages (if the format string uses them, e.g., {request_id}).
Example
>>> ASCIIColors.set_context(user_id="user123", session_id="abc") >>> logger.info("User action performed.") # If formatter includes {user_id}, it will appear in the output.
- Parameters:
**kwargs (Any) – Keyword arguments representing the context variables to set.
- Return type:
None
- classmethod clear_context(*args)[source]¶
Clears specified keys (or all keys) from the current thread’s logging context.
- Parameters:
*args (str) – Optional names of context keys to remove. If no arguments are provided, all context variables currently set for the thread (that don’t start with ‘_’) are removed.
- Return type:
None
- classmethod context(**kwargs)[source]¶
Context manager to temporarily add thread-local context variables.
Sets the provided keyword arguments as context variables upon entering the with block and restores the previous context state (removing added keys or restoring previous values) upon exiting the block, ensuring context isolation.
Example
>>> with ASCIIColors.context(request_id="req-001"): ... logger.info("Processing request.") # Log will include request_id >>> # request_id is now removed from context outside the block
- Parameters:
**kwargs (Any) – Keyword arguments representing the context variables to set temporarily within the with block.
- Yields:
None
- Return type:
ContextManager[None]
- classmethod get_thread_context()[source]¶
Returns a dictionary containing the current thread’s logging context variables.
This is used internally by formatters but can also be called manually for debugging or inspection.
Color and Style Constants
Provides numerous constants like
color_red
,style_bold
,bg_blue
. See the Available Colors and Styles section in the Usage Guide guide for a full list.Warning
Deprecated methods
set_log_file
andset_template
should not be used. Useadd_handler()
withFileHandler
andsetFormatter()
respectively.Concealed/hidden text style (support varies).
- classmethod set_log_level(level)[source]¶
Sets the global minimum log level for the entire logging system.
Messages with a severity lower than this level will be ignored and not processed by any handlers.
- Parameters:
level (LogLevel | int) – The minimum log level (LogLevel enum or int) to set globally.
- Return type:
None
- classmethod add_handler(handler)[source]¶
Adds a Handler instance to the global list of handlers.
All log records that pass the global level filter will be processed by this handler (subject to the handler’s own level filter).
- Parameters:
handler (Handler) – The Handler instance to add.
- Return type:
None
- classmethod remove_handler(handler)[source]¶
Removes a specific Handler instance from the global list.
- Parameters:
handler (Handler) – The Handler instance to remove. If the handler is not found, this method does nothing.
- Return type:
None
- classmethod clear_handlers()[source]¶
Removes all configured handlers from the global list.
Note: This does not automatically call the close() method on the removed handlers. If handlers manage resources (like files), they should be closed explicitly or via basicConfig(force=True).
- Return type:
None
- classmethod set_log_file(path, level=10, formatter=None)[source]¶
[DEPRECATED] Adds a FileHandler for the specified path.
Warning: This method is deprecated. Use add_handler(FileHandler(…)) instead for better clarity and consistency.
- classmethod set_template(level, template)[source]¶
[DEPRECATED] Sets a format template (string) for a specific level.
Warning: This method is deprecated and its functionality was limited. Use handler.setFormatter(Formatter(…)) on specific handler instances to control formatting. It does not work as expected with the current handler/formatter model.
- Parameters:
level (LogLevel)
template (str)
- Return type:
None
- classmethod set_context(**kwargs)[source]¶
Sets key-value pairs in the current thread’s logging context.
These context variables will be included in the log_record dictionary passed to formatters, allowing them to be included in log messages (if the format string uses them, e.g., {request_id}).
Example
>>> ASCIIColors.set_context(user_id="user123", session_id="abc") >>> logger.info("User action performed.") # If formatter includes {user_id}, it will appear in the output.
- Parameters:
**kwargs (Any) – Keyword arguments representing the context variables to set.
- Return type:
None
- classmethod clear_context(*args)[source]¶
Clears specified keys (or all keys) from the current thread’s logging context.
- Parameters:
*args (str) – Optional names of context keys to remove. If no arguments are provided, all context variables currently set for the thread (that don’t start with ‘_’) are removed.
- Return type:
None
- classmethod context(**kwargs)[source]¶
Context manager to temporarily add thread-local context variables.
Sets the provided keyword arguments as context variables upon entering the with block and restores the previous context state (removing added keys or restoring previous values) upon exiting the block, ensuring context isolation.
Example
>>> with ASCIIColors.context(request_id="req-001"): ... logger.info("Processing request.") # Log will include request_id >>> # request_id is now removed from context outside the block
- Parameters:
**kwargs (Any) – Keyword arguments representing the context variables to set temporarily within the with block.
- Yields:
None
- Return type:
ContextManager[None]
- classmethod get_thread_context()[source]¶
Returns a dictionary containing the current thread’s logging context variables.
This is used internally by formatters but can also be called manually for debugging or inspection.
- classmethod debug(message, *args, **kwargs)[source]¶
Logs a message with level DEBUG using the configured logging system.
- classmethod info(message, *args, **kwargs)[source]¶
Logs a message with level INFO using the configured logging system.
- classmethod warning(message, *args, **kwargs)[source]¶
Logs a message with level WARNING using the configured logging system.
- classmethod error(message, *args, exc_info=None, **kwargs)[source]¶
Logs a message with level ERROR using the configured logging system.
- Parameters:
message (str) – The log message (can be a format string).
*args (Any) – Arguments for %-formatting of the message.
exc_info (bool | BaseException | Tuple[Type[BaseException] | None, BaseException | None, Any] | None) – Optional exception information to include (None, True, Exception, tuple).
**kwargs (Any) – Extra context data.
- Return type:
None
- classmethod critical(message, *args, **kwargs)[source]¶
Logs a message with level CRITICAL using the configured logging system.
- static print(text, color='\x1b[37m', style='', background='', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Prints text directly to a stream with specified color, style, and background.
This method bypasses the entire logging system (handlers, formatters, levels, context). It’s a direct wrapper around the built-in print.
- Parameters:
text (str) – The string to print.
color (str) – ANSI foreground color code (e.g., ASCIIColors.color_red). Defaults to color_white.
style (str) – ANSI style code(s) (e.g., ASCIIColors.style_bold). Multiple styles can be concatenated (e.g., style_bold + style_underline). Defaults to “”.
background (str) – ANSI background color code (e.g., ASCIIColors.color_bg_blue). Defaults to “”.
end (str) – String appended after the text. Defaults to newline (n).
flush (bool) – Whether to forcibly flush the stream. Defaults to False.
file (TextIO | IO[str]) – The stream to write to. Defaults to sys.stdout.
- Return type:
None
- static success(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in green color.
- static fail(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in red color.
- static black(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in black color.
- static red(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in red color.
- static green(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in green color.
- static yellow(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in yellow color.
- static blue(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in blue color.
- static magenta(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in magenta color.
- static cyan(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in cyan color.
- static white(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in white color.
- static orange(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in orange color (256-color approx).
- static bright_black(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright black (gray) color.
- static bright_red(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright red color.
- static bright_green(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright green color.
- static bright_yellow(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright yellow color.
- static bright_blue(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright blue color.
- static bright_magenta(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright magenta color.
- static bright_cyan(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright cyan color.
- static bright_white(text, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bright white color.
- static print_with_bg(text, color='\x1b[37m', background='', style='', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
[DEPRECATED] Helper to print with background; use ASCIIColors.print() with background parameter instead. Directly prints text with specified foreground color, background color, and style.
- static bg_black(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a black background.
- static bg_red(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a red background.
- static bg_green(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a green background.
- static bg_yellow(text, color='\x1b[30m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a yellow background (default text: black).
- static bg_blue(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a blue background.
- static bg_magenta(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a magenta background.
- static bg_cyan(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a cyan background.
- static bg_white(text, color='\x1b[30m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a white background (default text: black).
- static bg_orange(text, color='\x1b[30m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with an orange background (256-color approx, default text: black).
- static bg_bright_black(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright black (gray) background.
- static bg_bright_red(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright red background.
- static bg_bright_green(text, color='\x1b[30m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright green background (default text: black).
- static bg_bright_yellow(text, color='\x1b[30m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright yellow background (default text: black).
- static bg_bright_blue(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright blue background.
- static bg_bright_magenta(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright magenta background.
- static bg_bright_cyan(text, color='\x1b[30m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright cyan background (default text: black).
- static bg_bright_white(text, color='\x1b[30m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text with a bright white background (default text: black).
- static bold(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in bold style.
- static dim(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in dim style.
- static italic(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in italic style.
- static underline(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in underline style.
- static blink(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in blinking style.
- static reverse(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in reverse video style.
- static hidden(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in hidden style.
- static strikethrough(text, color='\x1b[37m', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text in strikethrough style.
- static multicolor(texts, colors, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints multiple text segments with corresponding colors on one line.
This method bypasses the logging system. Each text segment in texts is printed using the corresponding color code from colors. A single reset code is added at the very end.
- Parameters:
texts (List[str]) – A list of strings to print sequentially.
colors (List[str]) – A list of ANSI color/style codes, corresponding to texts. Must have the same length as texts.
end (str) – String appended after all segments. Defaults to newline (n).
flush (bool) – Whether to forcibly flush the stream. Defaults to False.
file (TextIO | IO[str]) – The stream to write to. Defaults to sys.stdout.
- Return type:
None
- static highlight(text, subtext, color='\x1b[37m', highlight_color='\x1b[33m', whole_line=False, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Directly prints text, highlighting occurrences of subtext(s).
This method bypasses the logging system. It searches for subtext within text and applies highlight_color to the matches.
- Parameters:
text (str) – The main string to print.
subtext (str | List[str]) – The string or list of strings to highlight within text.
color (str) – The default ANSI color code for non-highlighted parts of text. Defaults to color_white.
highlight_color (str) – The ANSI color/style code to apply to matched subtext. Defaults to color_yellow. Can include styles/backgrounds.
whole_line (bool) – If True, highlight the entire line if any part of subtext is found in it. If False (default), only highlight the matched subtext itself.
end (str) – String appended after the text. Defaults to newline (n).
flush (bool) – Whether to forcibly flush the stream. Defaults to False.
file (TextIO | IO[str]) – The stream to write to. Defaults to sys.stdout.
- Return type:
None
- static activate(color_or_style, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Activates a specific ANSI color or style directly on the stream.
This method bypasses the logging system. It prints the given ANSI code without any text or reset code afterwards. Useful for setting a style that persists across multiple subsequent prints until reset() is called.
- static reset(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Resets all active ANSI colors and styles directly on the stream.
This method bypasses the logging system. It prints the color_reset code.
- static resetAll(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Alias for reset().
- static execute_with_animation(pending_text, func, *args, color=None, **kwargs)[source]¶
Executes a function while displaying a console spinner animation.
This utility uses direct printing (ASCIIColors.print) to show and update the spinner animation on sys.stdout. It runs the provided func in a separate thread. Once the function completes (or raises an exception), the animation stops, a final status (success ✓ or failure ✗) is printed, and the function’s result is returned or its exception is re-raised.
Note: Log messages generated within the executed func will still go through the standard logging system and appear separately from the spinner line.
- Parameters:
pending_text (str) – The text message to display next to the spinner (e.g., “Processing…”).
func (Callable[[...], _T]) – The callable (function or method) to execute.
*args (Any) – Positional arguments to pass to func.
color (str | None) – Optional ANSI color code for the pending_text. Defaults to yellow.
**kwargs (Any) – Keyword arguments to pass to func.
- Returns:
The return value of the executed func.
- Raises:
Exception – Re-raises any exception raised by the executed func.
- Return type:
_T
Example
>>> result = ASCIIColors.execute_with_animation("Loading data...", time.sleep, 2) # Displays "Loading data... [spinner]" for 2 seconds, then success status.
- static confirm(question, default_yes=None, prompt_color='\x1b[33m', file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Asks a yes/no question via direct terminal interaction and returns the result.
Handles ‘y/yes’ and ‘n/no’ (case-insensitive) input. Supports setting a default response if the user just presses Enter. Re-prompts on invalid input. Uses direct printing, bypassing the logging system.
- Parameters:
question (str) – The question text to display.
default_yes (bool | None) – If True, Enter defaults to Yes. If False, Enter defaults to No. If None, Enter is invalid input and requires y/n.
prompt_color (str) – ANSI color code for the question and prompt suffix.
file (TextIO | IO[str]) – The stream to write the prompt to and read input from.
- Returns:
True if the user confirmed (yes), False otherwise (no).
- Return type:
- static prompt(prompt_text, color='\x1b[32m', style='', hide_input=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Displays a prompt and reads a line of text input from the user.
Uses direct printing for the prompt, bypassing the logging system. Can optionally hide the user’s input (e.g., for passwords).
- Parameters:
prompt_text (str) – The text to display before the input cursor.
color (str) – ANSI color code for the prompt text.
style (str) – ANSI style code for the prompt text.
hide_input (bool) – If True, the input characters will not be echoed to the terminal (uses getpass). Defaults to False.
file (TextIO | IO[str]) – The stream to write the prompt to. Note: getpass typically reads directly from the tty, potentially bypassing this file argument for the input part when hide_input is True.
- Returns:
The string entered by the user. Returns an empty string if the user cancels with Ctrl+C during input().
- Return type:
Logging Compatibility API¶
Functions designed to mimic Python’s standard logging
module for easy integration and familiarity. These operate on the global state managed by ASCIIColors
.
- ascii_colors.getLogger(name=None)[source]¶
Returns a logger adapter instance with the specified name. Mimics logging.getLogger.
If name is None or “root”, the root logger adapter is returned. Subsequent calls with the same name will return the same cached adapter instance.
- Parameters:
name (str | None) – The hierarchical name of the logger (e.g., “myapp.ui”, “db.connector”). If None, returns the root logger adapter.
- Returns:
An _AsciiLoggerAdapter instance configured to use the global ascii_colors logging state.
- Return type:
_AsciiLoggerAdapter
- ascii_colors.basicConfig(**kwargs)[source]¶
Performs basic configuration for the ascii_colors logging system. Mimics logging.basicConfig.
This function configures the global logging state (level, handlers, formatters) based on the provided keyword arguments. It’s intended to be called once at application startup. Subsequent calls typically have no effect unless force=True is specified.
If no handlers are specified via the handlers argument, it creates a default handler (ConsoleHandler/StreamHandler writing to stderr, or FileHandler if filename is provided). It sets the global level and applies a default formatter to the implicitly created handler(s).
- Supported Keyword Arguments:
- level (Union[int, str]): Sets the global minimum logging level (e.g., INFO, “DEBUG”).
Defaults to WARNING.
format (str): The format string for the default formatter (use fmt= alias too). datefmt (str): The date format string for the default formatter. style (str): The format string style (‘%’ or ‘{’) for the default formatter. Defaults to ‘%’. handlers (List[Handler]): A list of handler instances to use. If provided,
stream and filename arguments are ignored. Handlers in this list will have the default formatter assigned only if they don’t already have one set.
filename (Union[str, Path]): Creates a FileHandler for this path. Incompatible with handlers. filemode (str): Mode for FileHandler (‘a’ or ‘w’). Defaults to ‘a’. Requires filename. encoding (str): Encoding for FileHandler. Requires filename. delay (bool): Delay file opening for FileHandler. Defaults to False. Requires filename. stream (StreamType): Creates a ConsoleHandler writing to this stream. Incompatible
with handlers and filename. Defaults to sys.stderr if no stream/filename/handlers are provided.
- force (bool): If True, removes and closes any existing global handlers before
performing configuration. Allows re-running basicConfig. Defaults to False.
- Parameters:
kwargs (Any)
- Return type:
None
- ascii_colors.getLevelName(level)[source]¶
Return the textual representation of logging level ‘level’. Mimics logging.getLevelName.
If the level corresponds to a standard level (DEBUG, INFO, etc.), the uppercase name is returned. Otherwise, the string “Level {level}” is returned.
Level Constants
Standard logging level integer constants, available directly from the module or via the logging alias.
- ascii_colors.CRITICAL = 50¶
- ascii_colors.ERROR = 40¶
- ascii_colors.WARNING = 30¶
- ascii_colors.INFO = 20¶
- ascii_colors.DEBUG = 10¶
- ascii_colors.NOTSET = 0¶
Handler Classes¶
Handlers direct log records to the appropriate destination (e.g., console, file).
- class ascii_colors.Handler(level=10, formatter=None)[source]¶
Bases:
ABC
Abstract base class for all log handlers.
Handlers are responsible for dispatching log records to the appropriate destination (e.g., console, file, network socket). Each handler can have its own minimum logging level and formatter.
Subclasses must implement the emit method.
- Parameters:
level (LogLevel)
formatter (Formatter | None)
- level¶
The minimum severity level required for a record to be processed by this handler.
- Type:
LogLevel
- formatter¶
The formatter instance used to convert log records to strings. If None, a default formatter may be used during handle.
- Type:
Optional[Formatter]
- _lock¶
A thread lock to ensure thread-safe operations (like emit).
- Type:
Lock
- level: LogLevel¶
- setLevel(level)[source]¶
Sets the minimum logging level for this handler.
- Parameters:
level (LogLevel | int) – The new minimum level (LogLevel enum or int).
- Return type:
None
- setFormatter(formatter)[source]¶
Sets the Formatter for this handler.
- Parameters:
formatter (Formatter) – The Formatter instance to use.
- Return type:
None
- getFormatter()[source]¶
Gets the Formatter for this handler (may be None).
- Return type:
Formatter | None
- set_formatter(formatter)[source]¶
Alias for setFormatter.
- Parameters:
formatter (Formatter)
- Return type:
None
- handle(level, message, timestamp, exc_info, logger_name='root', **kwargs)[source]¶
Conditionally processes a log record.
Checks if the record’s level meets the handler’s threshold. If it does, it formats the record using its formatter (or a default one if none is set) and then calls the emit method to dispatch it.
- Parameters:
level (LogLevel) – The level of the log record being handled.
message (str) – The primary message string.
timestamp (datetime) – The time the record was created.
exc_info (Tuple[Type[BaseException] | None, BaseException | None, Any] | None) – Exception information tuple, or None.
logger_name (str) – The name of the logger originating the record.
**kwargs (Any) – Additional context data.
- Return type:
None
- abstractmethod emit(level, formatted_message)[source]¶
Sends the formatted log record to the destination.
This method must be implemented by subclasses. It defines the actual output action (e.g., writing to a stream, sending over network).
- Parameters:
level (LogLevel) – The severity level of the message being emitted (can be used by subclass for level-specific actions, e.g., coloring).
formatted_message (str) – The final, formatted string to be output.
- Raises:
NotImplementedError – If called on the base Handler class.
- Return type:
None
- class ascii_colors.FileHandler(filename, mode='a', encoding='utf-8', delay=False, level=10, formatter=None)[source]¶
Bases:
Handler
Handles logging records by writing them to a file.
- Parameters:
- filename¶
The absolute path to the log file.
- Type:
Path
- delay¶
If True, file opening is deferred until the first message is emitted. Defaults to False.
- Type:
- __init__(filename, mode='a', encoding='utf-8', delay=False, level=10, formatter=None)[source]¶
Initializes the file handler.
- Parameters:
filename (str | Path) – The path to the log file (string or Path object).
mode (str) – File opening mode. Defaults to ‘a’ (append). ‘w’ overwrites.
encoding (str | None) – File encoding. Defaults to “utf-8”. If None, system default is used.
delay (bool) – If True, defer opening the file until the first log record is emitted. Defaults to False (open immediately).
level (LogLevel | int) – The minimum logging level for this handler. Defaults to DEBUG.
formatter (Formatter | None) – The formatter instance to use. Defaults to None (a default Formatter will be used in handle).
- Raises:
ValueError – If the mode is invalid.
OSError – If the file cannot be opened immediately (and delay is False).
- emit(level, formatted_message)[source]¶
Writes the formatted message to the log file.
If delay was True and the file isn’t open yet, it attempts to open it first. Handles potential errors during writing or flushing.
- Parameters:
level (LogLevel) – The severity level (not used directly by FileHandler emit).
formatted_message (str) – The pre-formatted log message string.
- Return type:
None
- ascii_colors.handlers¶
- A namespace providing access to handler classes (e.g., ``handlers.RotatingFileHandler``), similar to ``logging.handlers``.
Formatter Classes¶
Formatters define the structure and content of the final log message string.
- class ascii_colors.Formatter(fmt=None, datefmt=None, style='%', include_source=False, **kwargs)[source]¶
Bases:
object
Base class for formatting log records into textual representations.
This class converts the internal log record details (level, message, timestamp, source info, context, etc.) into a final string suitable for output by a Handler. It supports both traditional ‘%’ style and modern ‘{}’ style format strings, drawing inspiration and compatibility from Python’s standard logging.Formatter.
- fmt¶
The format string definition. If None, a default format is used based on the style.
- Type:
Optional[str]
- datefmt¶
The format string for timestamps (used with ‘asctime’). Defaults to “%Y-%m-%d %H:%M:%S,%f” (milliseconds included).
- Type:
- include_source¶
If True, attempts to automatically determine and include source code information (filename, lineno, funcName) in the log record. This incurs performance overhead due to stack inspection. Defaults to False.
- Type:
- __init__(fmt=None, datefmt=None, style='%', include_source=False, **kwargs)[source]¶
Initializes the Formatter instance.
- Parameters:
fmt (str | None) – The format string. If None, a default format string is used: ‘%(levelname)s:%(name)s:%(message)s’ for style=’%’, or ‘{levelname}:{name}:{message}’ for style=’{‘.
datefmt (str | None) – The date format string for the ‘asctime’ field. If None, defaults to “%Y-%m-%d %H:%M:%S,%f”, usually displayed with milliseconds truncated (e.g., “%Y-%m-%d %H:%M:%S,fff”).
style (str) – The formatting style to use. Must be ‘%’ or ‘{’. Defaults to ‘%’.
include_source (bool) – If True, attempt to find the source file, line number, and function name of the log call site. This involves inspecting the call stack and adds significant overhead. Defaults to False.
**kwargs (Any) – Absorbs any extra keyword arguments for potential future use or compatibility.
- format(level, message, timestamp, exc_info, logger_name='root', **kwargs)[source]¶
Formats the log record data into the final output string.
This method is called by Handlers to turn the raw log information into a formatted string based on the formatter’s configuration (fmt, style, datefmt, include_source).
- Parameters:
level (LogLevel) – The severity level of the log record (e.g., LogLevel.INFO).
message (str) – The primary log message string (after any %-style args merge).
timestamp (datetime) – The datetime object when the logging call was made.
exc_info (Tuple[Type[BaseException] | None, BaseException | None, Any] | None) – Exception tuple (type, value, traceback) if exception info is present, otherwise None.
logger_name (str) – The name of the logger that issued the record.
**kwargs (Any) – Any additional context or data passed with the logging call (e.g., using logger.info(“msg”, extra={‘key’: ‘val’}) or context variables from ASCIIColors.context).
- Returns:
The fully formatted log record string.
- Return type:
- format_exception(exc_info)[source]¶
Formats the specified exception information as a traceback string.
- Parameters:
exc_info (Tuple[Type[BaseException] | None, BaseException | None, Any]) – A tuple (type, value, traceback) as returned by sys.exc_info().
- Returns:
A string representing the formatted traceback, or an empty string if no valid exception information is provided.
- Return type:
- class ascii_colors.JSONFormatter(fmt=None, datefmt=None, style='%', json_ensure_ascii=False, json_indent=None, json_separators=None, json_sort_keys=False, include_fields=None, include_source=False, **kwargs)[source]¶
Bases:
Formatter
Formats log records into JSON strings.
This formatter serializes the log record dictionary (potentially selecting or renaming fields) into a JSON formatted string, making logs easily parsable by other systems.
- Parameters:
- fmt_dict¶
A dictionary mapping output JSON keys to format strings (using style). If set, include_fields is ignored.
- include_fields¶
A list of standard log record keys to include in the JSON output. If None and fmt_dict is None, a default set of fields is used.
- Type:
Optional[List[str]]
- datefmt_str¶
The date format string. If None or “iso”, uses ISO 8601 format. Otherwise, uses strftime with the given format.
- Type:
Optional[str]
- json_ensure_ascii¶
Passed to json.dumps. If True (default), non-ASCII characters are escaped.
- Type:
- json_indent¶
Passed to json.dumps. If not None, pretty-prints JSON with the specified indent level.
- Type:
Optional[int]
- json_separators¶
Passed to json.dumps. Overrides default separators (e.g., (‘,’, ‘: ‘)).
- include_source¶
If True, attempts to include source code info (filename, lineno, funcName). Adds overhead.
- Type:
- __init__(fmt=None, datefmt=None, style='%', json_ensure_ascii=False, json_indent=None, json_separators=None, json_sort_keys=False, include_fields=None, include_source=False, **kwargs)[source]¶
Initializes the JSONFormatter instance.
- Parameters:
fmt (Dict[str, str] | None) – A dictionary mapping desired output JSON keys to format strings (which will be processed using the specified style). Example: {‘timestamp’: ‘%(asctime)s’, ‘level’: ‘%(levelname)s’, ‘msg’: ‘%(message)s’}. If provided, include_fields is ignored.
datefmt (str | None) – Date format string. Special value “iso” (default) uses ISO 8601 format (datetime.isoformat()). Otherwise, uses strftime.
style (str) – The formatting style (‘%’ or ‘{’) to use if fmt (the dict) is provided and contains complex format strings that need evaluation. Defaults to ‘%’.
json_ensure_ascii (bool) – Corresponds to ensure_ascii in json.dumps. Defaults to False.
json_indent (int | None) – Corresponds to indent in json.dumps. Defaults to None.
json_separators (Tuple[str, str] | None) – Corresponds to separators in json.dumps. Defaults to None.
json_sort_keys (bool) – Corresponds to sort_keys in json.dumps. Defaults to False.
include_fields (List[str] | None) – A list of log record attribute names to include in the final JSON object (e.g., [“levelname”, “message”, “timestamp”]). If fmt is None and include_fields is None, a default set of fields is used.
include_source (bool) – If True, attempt to find source file/line/func information. Adds overhead. Defaults to False.
**kwargs (Any) – Absorbs extra keyword arguments.
- format(level, message, timestamp, exc_info, logger_name='root', **kwargs)[source]¶
Formats the log record into a JSON string.
Constructs a dictionary representing the log record based on the formatter’s configuration (fmt_dict, include_fields, include_source) and then serializes it to a JSON string using the specified options.
- Parameters:
level (LogLevel) – The severity level of the log record.
message (str) – The primary log message string.
timestamp (datetime) – The datetime object when the logging call occurred.
exc_info (Tuple[Type[BaseException] | None, BaseException | None, Any] | None) – Exception tuple (type, value, traceback), or None.
logger_name (str) – The name of the logger.
**kwargs (Any) – Additional context or data passed with the logging call.
- Returns:
A string containing the JSON representation of the log record. Returns a JSON error object if serialization fails.
- Return type:
Utility Functions¶
- ascii_colors.get_trace_exception(ex)[source]¶
Formats a given exception object and its traceback into a single string.
This utility is useful for consistently formatting exception details, often used within formatters or when manually logging exception information.
- Parameters:
ex (BaseException) – The exception instance to format.
- Returns:
A string containing the formatted exception type, message, and traceback.
- Return type:
- ascii_colors.trace_exception(ex)[source]¶
Logs the traceback of a given exception using the configured logging system.
This is a convenience function that calls ASCIIColors.error with the exception type as part of the message and sets exc_info to the exception instance, ensuring the traceback is captured and formatted by handlers.
- Parameters:
ex (BaseException) – The exception instance to log.
- Return type:
None