Your goto Python logging without panic on context switch
npx @tessl/cli install tessl/pypi-alog@1.2.0Your goto Python logging without panic on context switch. Alog is a simplified Python logging library that provides instant logging capabilities with sensible defaults, eliminating the need for manual logger setup and configuration in each module.
pip install alogimport alogFor accessing specific logging levels:
from alog import INFO, ERROR, WARNING, DEBUG, CRITICALFor advanced usage with custom loggers:
from alog import Alogger, init_alogger, default_alog_config, StreamHandlerimport alog
# Simple logging - no setup required
alog.info("Application started")
alog.error("Something went wrong")
alog.debug("Debug information")
# Pretty print complex objects
data = {"users": [1, 2, 3], "status": "active"}
alog.info(alog.pformat(data))
# Inspect object attributes
class MyClass:
def __init__(self):
self.public_attr = "visible"
self._private_attr = "hidden"
obj = MyClass()
alog.info(alog.pdir(obj)) # Shows only public attributes
# Configure logging behavior
alog.set_level("DEBUG")
alog.turn_logging_datetime(on=True)
alog.turn_logging_thread_name(on=True)
alog.turn_logging_process_id(on=True)Alog is built on Python's standard logging module with these key components:
The library automatically detects module names and formats log messages with clean, readable output showing file paths and line numbers without requiring manual logger initialization.
Standard logging functions that work out-of-the-box without any configuration.
def critical(msg, *args, **kwargs):
"""Log a message with severity 'CRITICAL'."""
def fatal(msg, *args, **kwargs):
"""Log a message with severity 'CRITICAL' (alias for critical)."""
def error(msg, *args, **kwargs):
"""Log a message with severity 'ERROR'."""
def exception(msg, *args, exc_info=None, **kwargs):
"""Log a message with severity 'ERROR', with exception info."""
def warning(msg, *args, **kwargs):
"""Log a message with severity 'WARNING'."""
def warn(msg, *args, **kwargs):
"""Log a message with severity 'WARNING' (alias for warning)."""
def info(msg, *args, **kwargs):
"""Log a message with severity 'INFO'."""
def debug(msg, *args, **kwargs):
"""Log a message with severity 'DEBUG'."""
def log(level, msg, *args, **kwargs):
"""Log 'msg % args' with the specified severity 'level'."""Control logging behavior and output formatting.
def set_level(level, alogger=None):
"""
Set the effective level for logging.
Parameters:
- level: int or str, logging level (e.g., 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
- alogger: Alogger instance, optional (defaults to global logger)
"""
def get_level(alogger=None):
"""
Get the effective level for logging.
Parameters:
- alogger: Alogger instance, optional (defaults to global logger)
Returns:
int | None: Current logging level from handlers, or None if no level set
"""
def turn_logging_datetime(on, alogger=None):
"""
Enable or disable datetime in log output.
Parameters:
- on: bool, whether to show datetime
- alogger: Alogger instance, optional (defaults to global logger)
"""
def turn_logging_thread_name(on, alogger=None):
"""
Enable or disable thread name in log output.
Parameters:
- on: bool, whether to show thread name
- alogger: Alogger instance, optional (defaults to global logger)
"""
def turn_logging_process_id(on, alogger=None):
"""
Enable or disable process ID in log output.
Parameters:
- on: bool, whether to show process ID
- alogger: Alogger instance, optional (defaults to global logger)
"""
def disable(level, alogger=None):
"""
Disable logging calls of specified severity 'level' and below.
Parameters:
- level: int or str, logging level to disable
- alogger: Alogger instance, optional (defaults to global logger)
"""Customize log output formatting and appearance.
def set_format(fs, alogger=None, is_default=False, time_strfmt="%Y-%m-%d %H:%M:%S"):
"""
Set the format string for log output.
Parameters:
- fs: str, format string for log messages
- alogger: Alogger instance, optional (defaults to global logger)
- is_default: bool, whether this is a default format
- time_strfmt: str, datetime format string
"""
def get_format(alogger=None):
"""
Get the current format (deprecated, use get_formatter).
Parameters:
- alogger: Alogger instance, optional (defaults to global logger)
Returns:
Formatter: Current formatter object
"""
def set_formatter(formatter, alogger=None):
"""
Set a custom formatter object.
Parameters:
- formatter: logging.Formatter instance
- alogger: Alogger instance, optional (defaults to global logger)
"""
def get_formatter(alogger=None):
"""
Get the current formatter object.
Parameters:
- alogger: Alogger instance, optional (defaults to global logger)
Returns:
logging.Formatter: Current formatter
"""
def set_root_name(root_name, alogger=None):
"""
Set the root name for path formatting.
Parameters:
- root_name: str, root directory name for path display
- alogger: Alogger instance, optional (defaults to global logger)
"""Built-in utilities for pretty printing and object inspection.
def pformat(*args, **kwargs):
"""
Pretty format objects using pprint with newline prefix.
Parameters:
- *args: objects to format
- **kwargs: options passed to pprint.pformat
Returns:
str: Pretty formatted string with leading newline
"""
def pdir(obj, str_not_startswith="_"):
"""
Pretty format object directory, filtering attributes by prefix.
Parameters:
- obj: object to inspect
- str_not_startswith: str, filter out attributes starting with this string
Returns:
str: Pretty formatted list of object attributes
"""Advanced functions for managing logger instances and configuration.
def getLogger(*args, **kwargs):
"""
Get the default logger (ignores arguments, shows warning if provided).
Returns:
Alogger: The default global logger instance
"""
def init_alogger(alog_config, default_root_name=None):
"""
Initialize a new Alogger instance with configuration.
Parameters:
- alog_config: dict, configuration dictionary
- default_root_name: str, optional root name for path formatting
Returns:
Alogger: Configured logger instance
"""
def default_alog_config():
"""
Get the default alog configuration dictionary.
Returns:
dict: Default configuration with format strings and options
"""
def reset_global_alog():
"""
Reset the global alog configuration and default logger.
"""For users who need direct access to the underlying logger class.
class Alogger:
"""
Enhanced Logger subclass with context-aware formatting and convenience methods.
"""
def __init__(self, root_name, *args, **kwargs):
"""
Initialize Alogger instance.
Parameters:
- root_name: str, root name for path formatting
- *args: additional arguments passed to Logger
- **kwargs: additional keyword arguments passed to Logger
"""
def set_level(self, level, logger=None):
"""Set logging level for this logger and its handlers."""
def get_level(self, logger=None):
"""Get logging level from handlers."""
def set_formatter(self, formatter, alogger=None):
"""Set formatter for all handlers."""
def set_format(self, fs, alogger=None, is_default=False, time_strfmt="%Y-%m-%d %H:%M:%S"):
"""Set format string for all handlers."""
def get_formatter(self, logger=None):
"""Get formatter from handlers."""
def get_format(self, logger=None):
"""Get format (deprecated, use get_formatter)."""
def set_root_name(self, root_name, logger=None):
"""Set root name for path formatting."""
def turn_logging_datetime(self, on):
"""Enable/disable datetime in log output."""
def turn_logging_thread_name(self, on):
"""Enable/disable thread name in log output."""
def turn_logging_process_id(self, on):
"""Enable/disable process ID in log output."""
def disable(self, level):
"""Disable logging at specified level."""
@staticmethod
def pformat(*args, **kwargs):
"""Pretty format objects using pprint with newline prefix."""
@classmethod
def pdir(cls, obj, str_not_startswith="_"):
"""Pretty format object directory, filtering by prefix."""Logging level constants imported from Python's logging module.
CRITICAL: int = 50
ERROR: int = 40
WARNING: int = 30
INFO: int = 20
DEBUG: int = 10
# Note: FATAL is an alias for CRITICAL
fatal = critical # Function aliasGlobal objects available after import.
default_logger: Alogger # The global default logger instance
config: dict # Global configuration dictionary
StreamHandler: type # Stream handler class from logging moduleimport alog
alog.info("Application started")
alog.warning("This is a warning")
alog.error("An error occurred")import alog
# Set logging level
alog.set_level("DEBUG")
# Enable datetime and thread info
alog.turn_logging_datetime(on=True)
alog.turn_logging_thread_name(on=True)
# Custom format
alog.set_format("%(asctime)s [%(levelname)s] %(message)s")
alog.info("Configured logging message")import alog
# Pretty print complex data structures
data = {
"users": ["alice", "bob", "charlie"],
"config": {"debug": True, "timeout": 30},
"metrics": [1.5, 2.3, 4.7, 1.2]
}
alog.info("Application data:" + alog.pformat(data))
# Inspect object attributes
class DatabaseConnection:
def __init__(self):
self.host = "localhost"
self.port = 5432
self._password = "secret" # Won't be shown
db = DatabaseConnection()
alog.info("DB connection attributes:" + alog.pdir(db))import alog
from alog import StreamHandler
# Create custom logger with specific configuration
config = alog.default_alog_config()
config['showing_thread_name'] = True
custom_logger = alog.init_alogger(config, "myapp")
custom_logger.info("Message from custom logger")
# Direct Alogger usage with custom handler
from alog import Alogger
app_logger = Alogger("myapp")
handler = StreamHandler()
app_logger.addHandler(handler)
app_logger.info("Direct Alogger usage")