API Reference
This page contains the complete API reference for tinystructlog.
Core Functions
get_logger
- tinystructlog.get_logger(name: str, fmt: str | None = None, datefmt: str | None = None) Logger[source]
Get a configured logger with context support and colored output.
This is the main entry point for creating loggers in your application. The logger is pre-configured with: - Context filtering (ContextFilter) - Colored output (ColoredFormatter) - Environment-based log level (LOG_LEVEL env var, defaults to INFO) - Stdout output
- Parameters:
name – The logger name, typically __name__ of the calling module.
fmt – Optional log format string. Supports all standard logging format attributes. Defaults to DEFAULT_FORMAT (v0.1.0 compatible format). Use preset constants (MINIMAL_FORMAT, DETAILED_FORMAT, SIMPLE_FORMAT) or provide a custom format string.
datefmt – Optional date format string for %(asctime)s. Defaults to DEFAULT_DATEFMT (“%Y-%m-%d %H:%M:%S”).
- Returns:
A configured logging.Logger instance.
Examples
>>> # Default format (v0.1.0 compatible) >>> log = get_logger(__name__) >>> log.info("Application started")
>>> # Using preset formats >>> log = get_logger(__name__, fmt=MINIMAL_FORMAT) >>> log.info("Simple message") # Output: INFO: Simple message
>>> # Custom format >>> log = get_logger(__name__, fmt="[%(levelname)s] %(message)s") >>> log.info("Custom output")
>>> # With context >>> set_log_context(request_id="abc123") >>> log.info("Processing request")
- Environment Variables:
- LOG_LEVEL: Set the logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL).
Defaults to INFO if not set.
Note
Version 0.1.0 had an opinionated, hardcoded format. Starting with v0.1.1, you can customize the format while maintaining full backward compatibility.
set_log_context
- tinystructlog.set_log_context(**kwargs: Any) None[source]
Merge/override keys in the current logging context.
Context variables are automatically injected into all log records within the current async task or thread. This is useful for tracking requests, users, tenants, or any other identifiers throughout your application.
- Parameters:
**kwargs – Key-value pairs to add to the logging context. Values are automatically converted to strings.
Example
>>> set_log_context(user_id="123", tenant="acme") >>> log.info("User action") # Will include user_id and tenant in output
clear_log_context
- tinystructlog.clear_log_context(*keys: str) None[source]
Clear specific keys from context; if no keys provided, clear all.
- Parameters:
*keys – Optional keys to remove from context. If not provided, all context is cleared.
Example
>>> set_log_context(user_id="123", request_id="abc") >>> clear_log_context("request_id") # Remove only request_id >>> clear_log_context() # Remove all context
log_context
- tinystructlog.log_context(**kwargs: Any)[source]
Temporarily set context within a block; restores original context on exit.
This context manager allows you to temporarily add context variables that are automatically restored when the block exits, even if an exception occurs.
- Parameters:
**kwargs – Key-value pairs to temporarily add to the logging context.
Example
>>> log = get_logger(__name__) >>> with log_context(operation="cleanup"): ... log.info("Starting") # Includes operation=cleanup ... perform_cleanup() >>> log.info("Done") # operation context is removed
- Yields:
None
Formatters and Filters
ContextFilter
- class tinystructlog.ContextFilter(name='')[source]
Logging filter that injects context variables into log records.
This filter reads the current context from the ContextVar and: 1. Injects each context key as an attribute on the log record 2. Creates a ‘context’ attribute with space-separated key=value pairs 3. Creates a ‘context_str’ attribute formatted as “ [key=value …]”
The filter is automatically applied by get_logger() and enables context variables to be used in log format strings.
ColoredFormatter
- class tinystructlog.ColoredFormatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]
Custom formatter that adds ANSI colors to log levels for terminal output.
Format: [timestamp] [level] [module.funcName:lineno] [context] message
- Colors:
DEBUG: Cyan
INFO: Green
WARNING: Yellow
ERROR: Red
CRITICAL: Magenta
The source location and context are dimmed for better readability.
- COLORS = {'CRITICAL': '\x1b[35m', 'DEBUG': '\x1b[36m', 'ERROR': '\x1b[31m', 'INFO': '\x1b[32m', 'WARNING': '\x1b[33m'}
- RESET = '\x1b[0m'
- DIM = '\x1b[2m'
Complete Module Reference
contexlog - Minimalistic context-aware structured logging for Python.
This module provides thread-safe and async-aware logging utilities that allow you to attach contextual information to log records. Context is automatically propagated across async tasks and can be used to track requests, users, or any other identifiers throughout your application.
- Key Features:
Context variables using Python’s contextvars for async/thread safety
Automatic context injection into log records
Colored terminal output with ANSI codes
Zero runtime dependencies
Full type hint support
Example
>>> from tinystructlog import get_logger, set_log_context
>>> log = get_logger(__name__)
>>> set_log_context(user_id="123", request_id="abc")
>>> log.info("Processing request")
[2024-01-17 10:30:45] [INFO] [module.function:10] [request_id=abc user_id=123] Processing request
- tinystructlog.core.set_log_context(**kwargs: Any) None[source]
Merge/override keys in the current logging context.
Context variables are automatically injected into all log records within the current async task or thread. This is useful for tracking requests, users, tenants, or any other identifiers throughout your application.
- Parameters:
**kwargs – Key-value pairs to add to the logging context. Values are automatically converted to strings.
Example
>>> set_log_context(user_id="123", tenant="acme") >>> log.info("User action") # Will include user_id and tenant in output
- tinystructlog.core.clear_log_context(*keys: str) None[source]
Clear specific keys from context; if no keys provided, clear all.
- Parameters:
*keys – Optional keys to remove from context. If not provided, all context is cleared.
Example
>>> set_log_context(user_id="123", request_id="abc") >>> clear_log_context("request_id") # Remove only request_id >>> clear_log_context() # Remove all context
- tinystructlog.core.log_context(**kwargs: Any)[source]
Temporarily set context within a block; restores original context on exit.
This context manager allows you to temporarily add context variables that are automatically restored when the block exits, even if an exception occurs.
- Parameters:
**kwargs – Key-value pairs to temporarily add to the logging context.
Example
>>> log = get_logger(__name__) >>> with log_context(operation="cleanup"): ... log.info("Starting") # Includes operation=cleanup ... perform_cleanup() >>> log.info("Done") # operation context is removed
- Yields:
None
- class tinystructlog.core.ContextFilter(name='')[source]
Bases:
FilterLogging filter that injects context variables into log records.
This filter reads the current context from the ContextVar and: 1. Injects each context key as an attribute on the log record 2. Creates a ‘context’ attribute with space-separated key=value pairs 3. Creates a ‘context_str’ attribute formatted as “ [key=value …]”
The filter is automatically applied by get_logger() and enables context variables to be used in log format strings.
- class tinystructlog.core.ColoredFormatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]
Bases:
FormatterCustom formatter that adds ANSI colors to log levels for terminal output.
Format: [timestamp] [level] [module.funcName:lineno] [context] message
- Colors:
DEBUG: Cyan
INFO: Green
WARNING: Yellow
ERROR: Red
CRITICAL: Magenta
The source location and context are dimmed for better readability.
- COLORS = {'CRITICAL': '\x1b[35m', 'DEBUG': '\x1b[36m', 'ERROR': '\x1b[31m', 'INFO': '\x1b[32m', 'WARNING': '\x1b[33m'}
- RESET = '\x1b[0m'
- DIM = '\x1b[2m'
- tinystructlog.core.get_logger(name: str, fmt: str | None = None, datefmt: str | None = None) Logger[source]
Get a configured logger with context support and colored output.
This is the main entry point for creating loggers in your application. The logger is pre-configured with: - Context filtering (ContextFilter) - Colored output (ColoredFormatter) - Environment-based log level (LOG_LEVEL env var, defaults to INFO) - Stdout output
- Parameters:
name – The logger name, typically __name__ of the calling module.
fmt – Optional log format string. Supports all standard logging format attributes. Defaults to DEFAULT_FORMAT (v0.1.0 compatible format). Use preset constants (MINIMAL_FORMAT, DETAILED_FORMAT, SIMPLE_FORMAT) or provide a custom format string.
datefmt – Optional date format string for %(asctime)s. Defaults to DEFAULT_DATEFMT (“%Y-%m-%d %H:%M:%S”).
- Returns:
A configured logging.Logger instance.
Examples
>>> # Default format (v0.1.0 compatible) >>> log = get_logger(__name__) >>> log.info("Application started")
>>> # Using preset formats >>> log = get_logger(__name__, fmt=MINIMAL_FORMAT) >>> log.info("Simple message") # Output: INFO: Simple message
>>> # Custom format >>> log = get_logger(__name__, fmt="[%(levelname)s] %(message)s") >>> log.info("Custom output")
>>> # With context >>> set_log_context(request_id="abc123") >>> log.info("Processing request")
- Environment Variables:
- LOG_LEVEL: Set the logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL).
Defaults to INFO if not set.
Note
Version 0.1.0 had an opinionated, hardcoded format. Starting with v0.1.1, you can customize the format while maintaining full backward compatibility.