Async API Reference

AsyncLogger

AsyncLogger Interface for LogEverything

This module provides an async-optimized logger interface that leverages LogEverything’s async infrastructure for high-performance async applications.

Example usage:

from logeverything.asyncio import AsyncLogger

# Simple usage with automatic async setup
log = AsyncLogger()
log.info("Hello, async world!")

# Advanced usage with async-optimized configuration
log = AsyncLogger("my_async_app")
await log.configure(
    level="DEBUG",
    visual_mode=True,
    async_queue_size=5000,
    async_handlers=["console", "file"],
    file_path="async_app.log"
)

# Async contextual logging
async with log.context("Async Data Processing"):
    log.info("Starting async processing")
    await some_async_operation()
    log.debug("Async operation completed")
    log.info("Processing complete")

# Bound context for structured async logging
user_log = log.bind(user_id=123, session_id="async-abc-def")
user_log.info("Async user action performed")
class logeverything.asyncio.async_logger.AsyncLogger(name=None, auto_setup=True, _register=True, **config)[source]

Bases: BaseLogger

An async-optimized logger interface for LogEverything.

This class provides the same clean interface as Logger but is specifically designed for async applications with async-optimized defaults and native async context manager support.

Inherits from BaseLogger to provide a consistent API and enable extensibility.

Key Features:
  • Automatically enables async_mode=True (no need to specify)

  • Async-first configuration with await logger.configure()

  • Built-in async context managers (async with logger.verbose())

  • Optimized for high-performance async applications

  • AsyncQueueHandler configured by default for non-blocking logging

Usage:

Basic async logging:

logger = AsyncLogger()
logger.info("This logs asynchronously")

Async configuration:

await logger.configure(level="DEBUG", handlers=["file"])

Async context managers:

async with logger.verbose():
    logger.debug("Enhanced logging in this context")
class CenteredFormatter(fmt=None, datefmt=None)[source]

Bases: Formatter

Custom formatter that centers the levelname field.

format(record)[source]

Format the specified record as text.

The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

Return type:

str

async __aenter__()[source]

Async context manager entry.

Automatically marks logger as temporary if it wasn’t explicitly created by the user beforehand (i.e., created inline with ‘async with AsyncLogger(…)’).

Return type:

AsyncLogger

async __aexit__(exc_type, exc_val, exc_tb)[source]

Async context manager exit.

Only closes and cleans up system-created loggers. User-created loggers are left intact.

Return type:

None

__del__()[source]

Cleanup when async logger is deleted.

Uses the base class cleanup logic which properly checks _is_registered to avoid unregistering bound loggers that share the same name.

Return type:

None

__init__(name=None, auto_setup=True, _register=True, **config)[source]

Initialize the AsyncLogger with async-optimized configuration.

Parameters:
  • name (Optional[str]) – Logger name (default: automatic based on caller)

  • auto_setup (bool) – Whether to automatically setup async logging

  • _register (bool) – Whether to register this logger (internal parameter for bound loggers)

  • **config (Any) – Configuration options (level, async_queue_size, handlers, etc.)

async acritical(message, *args, **kwargs)[source]

Async critical logging (ensures async context is properly handled).

Return type:

None

async adebug(message, *args, **kwargs)[source]

Async debug logging (ensures async context is properly handled).

Return type:

None

async aerror(message, *args, **kwargs)[source]

Async error logging (ensures async context is properly handled).

Return type:

None

async aexception(message, *args, **kwargs)[source]

Async exception logging (ensures async context is properly handled).

Return type:

None

async ainfo(message, *args, **kwargs)[source]

Async info logging (ensures async context is properly handled).

Return type:

None

async awarning(message, *args, **kwargs)[source]

Async warning logging (ensures async context is properly handled).

Return type:

None

async close()[source]

Close the async logger and cleanup resources.

Return type:

None

async configure(**config)[source]

Configure the async logger with the specified options.

Parameters:

**config (Any) – Configuration options

Returns:

Self for method chaining

Return type:

AsyncLogger

context(context_name, **kwargs)[source]

Async context manager for hierarchical logging with automatic indentation.

Parameters:
  • context_name (str) – Name of the context for log messages

  • **kwargs (Any) – Additional context variables to bind

Return type:

AsyncGenerator[AsyncLogger, None]

Example

async with logger.context(“Data Processing”, batch_id=123):

await process_data()

critical(message, *args, **kwargs)[source]

Log a critical message.

Return type:

None

debug(message, *args, **kwargs)[source]

Log a debug message.

Return type:

None

error(message, *args, **kwargs)[source]

Log an error message.

Return type:

None

exception(message, *args, **kwargs)[source]

Log an exception message with traceback.

Return type:

None

handlers(handlers, **kwargs)[source]

Async context manager for temporary handler changes.

Parameters:

handlers (list) – List of handlers to use temporarily

Return type:

AsyncGenerator[AsyncLogger, None]

Example

async with logger.handlers([file_handler]):

await file_only_operation()

info(message, *args, **kwargs)[source]

Log an info message.

Return type:

None

property logger: Logger

Get the underlying Python logger instance.

property name: str

Get the logger name without the logeverything prefix.

quiet(**kwargs)[source]

Async context manager for quiet logging.

Example

async with logger.quiet():

await noisy_operation()

Return type:

AsyncGenerator[AsyncLogger, None]

verbose(**kwargs)[source]

Async context manager for verbose logging.

Example

async with logger.verbose():

await detailed_operation()

Return type:

AsyncGenerator[AsyncLogger, None]

visual(**kwargs)[source]

Async context manager for visual logging enhancements.

Example

async with logger.visual(use_symbols=True):

await important_operation()

Return type:

AsyncGenerator[AsyncLogger, None]

warn(message, *args, **kwargs)[source]

Log a warning message (alias for warning).

Return type:

None

warning(message, *args, **kwargs)[source]

Log a warning message.

Return type:

None

Async Decorators & Context Managers

Asynchronous support for the LogEverything library.

This module provides asynchronous logging capabilities, including: - Async-compatible handlers with non-blocking emit() methods - Queue-based log record processing - Async-compatible decorator for logging async functions - Task context tracking for proper indent management

Performance optimizations: - Lazy evaluation of expensive operations - Cached function metadata - Fast path for disabled logging - Reduced function call overhead

class logeverything.asyncio.async_logging.AsyncLoggingContext(level=None, log_entry_exit=None, log_arguments=None, log_return_values=None, beautify=None, indent_level=None, handlers=None, logger_name=None, capture_print=None, print_logger_name=None, print_level=None, print_prefix=None, **kwargs)[source]

Bases: object

An async context manager for temporarily modifying logging configuration.

This allows you to change logging settings within an async context and automatically restore the previous settings when exiting the context.

Example

>>> async with AsyncLoggingContext(level="DEBUG", log_entry_exit=True):
...     # Code here will use DEBUG level and log function entry/exit
...     await async_function()
... # Original settings are restored after the context
async __aenter__()[source]

Enter the async context, delegate to the synchronous context.

Returns:

The current configuration

Return type:

Dict[str, Any]

async __aexit__(exc_type, exc_val, exc_tb)[source]

Exit the async context, delegate to the synchronous context.

Parameters:
  • exc_type (Any) – Exception type if an exception was raised

  • exc_val (Any) – Exception value if an exception was raised

  • exc_tb (Any) – Exception traceback if an exception was raised

Return type:

None

__enter__()[source]

Support using this context in regular synchronous code as well.

Returns:

The current configuration

Return type:

Dict[str, Any]

__exit__(exc_type, exc_val, exc_tb)[source]

Support using this context in regular synchronous code as well.

Parameters:
  • exc_type (Any) – Exception type if an exception was raised

  • exc_val (Any) – Exception value if an exception was raised

  • exc_tb (Any) – Exception traceback if an exception was raised

Return type:

None

__init__(level=None, log_entry_exit=None, log_arguments=None, log_return_values=None, beautify=None, indent_level=None, handlers=None, logger_name=None, capture_print=None, print_logger_name=None, print_level=None, print_prefix=None, **kwargs)[source]

Initialize an async logging context with temporary configuration.

Parameters:
  • level (Union[int, str, None]) – Temporarily change the logging level

  • log_entry_exit (Optional[bool]) – Whether to log function entry and exit

  • log_arguments (Optional[bool]) – Whether to log function arguments

  • log_return_values (Optional[bool]) – Whether to log function return values

  • beautify (Optional[bool]) – Whether to beautify logs with visual elements

  • indent_level (Optional[int]) – Indentation level for beautified logs

  • handlers (Optional[List[str]]) – List of handlers to use temporarily

  • logger_name (Optional[str]) – Name of the logger to configure

  • capture_print (Optional[bool]) – Whether to capture print statements

  • print_logger_name (Optional[str]) – Logger name for captured print statements

  • print_level (Optional[int]) – Logging level for captured print statements

  • print_prefix (Optional[str]) – Prefix for captured print statements

  • **kwargs (Any) – Additional configuration options

class logeverything.asyncio.async_logging.AsyncQueueHandler(queue_size=1000, target_handlers=None, flush_level=50, flush_interval=1.0, name='async_handler')[source]

Bases: Handler

A logging handler that queues log records for asynchronous processing.

This handler places log records into a queue for processing by a separate worker thread, allowing the calling thread or task to continue execution without waiting for logging I/O to complete.

__init__(queue_size=1000, target_handlers=None, flush_level=50, flush_interval=1.0, name='async_handler')[source]

Initialize the AsyncQueueHandler.

Parameters:
  • queue_size (int) – Maximum number of records in the queue (default: 1000)

  • target_handlers (Optional[List[Handler]]) – Handlers to process records from the queue (default: None)

  • flush_level (int) – Records >= this level trigger immediate flush (default: CRITICAL)

  • flush_interval (float) – Seconds between background flushes (default: 1.0)

  • name (str) – Name for the handler and worker thread (default: “async_handler”)

close()[source]

Close the handler and shut down the worker thread.

This ensures all records are processed before shutting down.

Return type:

None

emit(record)[source]

Queue the record for asynchronous processing.

This is a non-blocking operation that returns immediately, allowing the calling code to continue execution without waiting for logging I/O.

Parameters:

record (LogRecord) – The LogRecord to process

Return type:

None

flush()[source]

Process all pending records in the queue.

This is a more expensive operation that ensures all records have been sent to the target handlers.

Return type:

None

class logeverything.asyncio.async_logging.AsyncQuietLoggingContext(level=30, log_entry_exit=False, log_arguments=False, log_return_values=False, capture_print=False, **kwargs)[source]

Bases: AsyncLoggingContext

An async context manager for temporarily suppressing logging output.

This is the async version of QuietLoggingContext, specialized for reducing log verbosity for async code blocks.

Example

>>> async with AsyncQuietLoggingContext():
...     # This code will produce minimal logs
...     await noisy_async_operation()
... # Original logging verbosity is restored after the context
__init__(level=30, log_entry_exit=False, log_arguments=False, log_return_values=False, capture_print=False, **kwargs)[source]

Initialize an async quiet logging context with minimized verbosity.

Parameters:
  • level (Union[int, str]) – The logging level to use (defaults to WARNING)

  • log_entry_exit (bool) – Whether to log function entry and exit (defaults to False)

  • log_arguments (bool) – Whether to log function arguments (defaults to False)

  • log_return_values (bool) – Whether to log function return values (defaults to False)

  • capture_print (bool) – Whether to capture print statements (defaults to False)

  • **kwargs (Any) – Additional configuration options

class logeverything.asyncio.async_logging.AsyncTemporaryHandlerContext(handlers)[source]

Bases: object

An async context manager for temporarily using specific log handlers.

This is the async version of TemporaryHandlerContext, allowing you to temporarily switch handlers for async code blocks.

Example

>>> async with AsyncTemporaryHandlerContext(["file", "json"]):
...     # This code will log to file and JSON, ignoring console
...     await important_async_operation()
... # Original handlers are restored after the context
async __aenter__()[source]

Enter the async context, delegate to the synchronous context.

Returns:

The current configuration

Return type:

Dict[str, Any]

async __aexit__(exc_type, exc_val, exc_tb)[source]

Exit the async context, delegate to the synchronous context.

Parameters:
  • exc_type (Any) – Exception type if an exception was raised

  • exc_val (Any) – Exception value if an exception was raised

  • exc_tb (Any) – Exception traceback if an exception was raised

Return type:

None

__enter__()[source]

Support using this context in regular synchronous code as well.

Returns:

The current configuration

Return type:

Dict[str, Any]

__exit__(exc_type, exc_val, exc_tb)[source]

Support using this context in regular synchronous code as well.

Parameters:
  • exc_type (Any) – Exception type if an exception was raised

  • exc_val (Any) – Exception value if an exception was raised

  • exc_tb (Any) – Exception traceback if an exception was raised

Return type:

None

__init__(handlers)[source]

Initialize an async temporary handler context.

Parameters:

handlers (List[Union[str, Handler]]) – A list of handler names or actual handler objects to use temporarily

class logeverything.asyncio.async_logging.AsyncVerboseLoggingContext(level=10, log_entry_exit=True, log_arguments=True, log_return_values=True, capture_print=True, **kwargs)[source]

Bases: AsyncLoggingContext

An async context manager for temporarily increasing logging verbosity.

This is the async version of VerboseLoggingContext, specialized for maximizing log information for async code blocks.

Example

>>> async with AsyncVerboseLoggingContext():
...     # This code will produce detailed logs
...     await complex_async_operation()
... # Original logging verbosity is restored after the context
__init__(level=10, log_entry_exit=True, log_arguments=True, log_return_values=True, capture_print=True, **kwargs)[source]

Initialize an async verbose logging context with maximum verbosity.

Parameters:
  • level (Union[int, str]) – The logging level to use (defaults to DEBUG)

  • log_entry_exit (bool) – Whether to log function entry and exit (defaults to True)

  • log_arguments (bool) – Whether to log function arguments (defaults to True)

  • log_return_values (bool) – Whether to log function return values (defaults to True)

  • capture_print (bool) – Whether to capture print statements (defaults to True)

  • **kwargs (Any) – Additional configuration options

class logeverything.asyncio.async_logging.AsyncVisualLoggingContext(visual_mode=True, use_symbols=None, use_indent=None, align_columns=None, color_theme=None, **kwargs)[source]

Bases: AsyncLoggingContext

An async context manager for temporarily enabling visual logging enhancements.

This is the async version of VisualLoggingContext, allowing you to enable colors, symbols, and other visual elements for a specific async code block.

Example

>>> async with AsyncVisualLoggingContext(use_symbols=True, color_theme="bold"):
...     # This code will have visual logging enhancements
...     await complex_visualization()
... # Original visual settings are restored after the context
__init__(visual_mode=True, use_symbols=None, use_indent=None, align_columns=None, color_theme=None, **kwargs)[source]

Initialize an async visual logging context with visual enhancements.

Parameters:
  • visual_mode (Optional[bool]) – Master switch for visual enhancements

  • use_symbols (Optional[bool]) – Whether to use Unicode symbols for log levels

  • use_indent (Optional[bool]) – Whether to use visual indentation with box drawing

  • align_columns (Optional[bool]) – Whether to align columns in log output

  • color_theme (Optional[str]) – Color theme to use for console output

  • **kwargs (Any) – Additional configuration options

logeverything.asyncio.async_logging.async_log_class(cls=None, using=None, **options)[source]

Decorator to apply async_log_function to all async methods in a class.

This decorator automatically wraps all coroutine methods in a class with the async_log_function decorator, while regular methods get the standard log_function decorator.

Parameters:
  • cls (Optional[Type]) – The class to decorate (automatically passed when used as @async_log_class)

  • using (Optional[str]) – Name of the LogEverything Logger instance to use for logging

  • **options (Any) – Decorator options that override default configuration

Return type:

Any

Returns:

The decorated class

logeverything.asyncio.async_logging.async_log_function(func=None, log_entry_exit=True, log_arguments=True, log_return_values=True, using=None, **options)[source]

Optimized decorator for logging entry, exit, and execution time of async functions.

Performance optimizations: - Fast path for disabled logging - Cached function metadata at decoration time - Reduced function call overhead - Optimized string building

Parameters:
  • func (Optional[TypeVar(F, bound= Callable[..., Any])]) – The async function to decorate (automatically passed when used as @async_log_function)

  • log_entry_exit (bool) – Enable/disable logging of function entry and exit

  • log_arguments (bool) – Enable/disable logging of function arguments

  • log_return_values (bool) – Enable/disable logging of return values

  • using (Optional[str]) – Name of the LogEverything Logger instance to use for logging

  • **options (Any) – Additional decorator options

Return type:

Union[TypeVar(F, bound= Callable[..., Any]), Callable[[TypeVar(F, bound= Callable[..., Any])], TypeVar(F, bound= Callable[..., Any])]]

Returns:

The decorated function

logeverything.asyncio.async_logging.cleanup_all_async_handlers()[source]

Close all registered AsyncQueueHandler instances.

Return type:

int

logeverything.asyncio.async_logging.cleanup_all_async_handlers_optimized()[source]

Close all registered AsyncQueueHandler instances with optimized batch processing.

Return type:

int

logeverything.asyncio.async_logging.decrement_async_indent()[source]

Decrement the indentation level for async functions.

Return type:

int

Returns:

The new indentation level

Note: This function now delegates to the unified IndentManager system.

logeverything.asyncio.async_logging.get_all_async_handlers()[source]

Get all currently active AsyncQueueHandler instances.

Return type:

List[AsyncQueueHandler]

logeverything.asyncio.async_logging.get_async_indent()[source]

Get the current indentation level for async functions.

Return type:

int

Returns:

The current indentation level

Note: This function now delegates to the unified IndentManager system.

logeverything.asyncio.async_logging.get_pooled_handler(queue_size=1000, target_handlers=None, flush_level=50, flush_interval=1.0)[source]

Get a reusable handler from the pool or create a new one.

Return type:

AsyncQueueHandler

logeverything.asyncio.async_logging.increment_async_indent()[source]

Increment the indentation level for async functions.

Returns: The new indentation level

Note: This function now delegates to the unified IndentManager system.

Return type:

int

logeverything.asyncio.async_logging.log_async_class(cls=None, using=None, **options)

Decorator to apply async_log_function to all async methods in a class.

This decorator automatically wraps all coroutine methods in a class with the async_log_function decorator, while regular methods get the standard log_function decorator.

Parameters:
  • cls (Optional[Type]) – The class to decorate (automatically passed when used as @async_log_class)

  • using (Optional[str]) – Name of the LogEverything Logger instance to use for logging

  • **options (Any) – Decorator options that override default configuration

Return type:

Any

Returns:

The decorated class

logeverything.asyncio.async_logging.log_async_function(func=None, log_entry_exit=True, log_arguments=True, log_return_values=True, using=None, **options)

Optimized decorator for logging entry, exit, and execution time of async functions.

Performance optimizations: - Fast path for disabled logging - Cached function metadata at decoration time - Reduced function call overhead - Optimized string building

Parameters:
  • func (Optional[TypeVar(F, bound= Callable[..., Any])]) – The async function to decorate (automatically passed when used as @async_log_function)

  • log_entry_exit (bool) – Enable/disable logging of function entry and exit

  • log_arguments (bool) – Enable/disable logging of function arguments

  • log_return_values (bool) – Enable/disable logging of return values

  • using (Optional[str]) – Name of the LogEverything Logger instance to use for logging

  • **options (Any) – Additional decorator options

Return type:

Union[TypeVar(F, bound= Callable[..., Any]), Callable[[TypeVar(F, bound= Callable[..., Any])], TypeVar(F, bound= Callable[..., Any])]]

Returns:

The decorated function

logeverything.asyncio.async_logging.return_handler_to_pool(handler)[source]

Return a handler to the pool for reuse.

Return type:

None