Abseil Python Common Libraries providing application startup utilities, command-line flag management, enhanced logging, and comprehensive testing utilities.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Comprehensive logging functionality built on Python's standard logging module with additional features including verbosity control, conditional logging, structured output formatting, and integration with the absl flag system.
Core logging functions for different severity levels with printf-style formatting support.
def debug(msg, *args, **kwargs):
"""
Log a debug message.
Args:
msg (str): Message format string
*args: Arguments for string formatting
**kwargs: Additional logging arguments (exc_info, extra, etc.)
"""
def info(msg, *args, **kwargs):
"""
Log an info message.
Args:
msg (str): Message format string
*args: Arguments for string formatting
**kwargs: Additional logging arguments
"""
def warning(msg, *args, **kwargs):
"""
Log a warning message.
Args:
msg (str): Message format string
*args: Arguments for string formatting
**kwargs: Additional logging arguments
"""
def warn(msg, *args, **kwargs):
"""Alias for warning() function."""
def error(msg, *args, **kwargs):
"""
Log an error message.
Args:
msg (str): Message format string
*args: Arguments for string formatting
**kwargs: Additional logging arguments
"""
def fatal(msg, *args, **kwargs):
"""
Log a fatal message and exit the program.
Args:
msg (str): Message format string
*args: Arguments for string formatting
**kwargs: Additional logging arguments
Note: This function calls sys.exit(1) after logging the message.
"""
def exception(msg, *args, exc_info=True, **kwargs):
"""
Log an exception message with traceback information.
Args:
msg (str): Message format string
*args: Arguments for string formatting
exc_info (bool): Include exception information (default True)
**kwargs: Additional logging arguments
"""General-purpose logging function for any severity level.
def log(level, msg, *args, **kwargs):
"""
Log a message at the specified level.
Args:
level (int): Logging level (DEBUG, INFO, WARNING, ERROR, FATAL)
msg (str): Message format string
*args: Arguments for string formatting
**kwargs: Additional logging arguments
"""Functions for controlling logging verbosity and checking current verbosity settings.
def get_verbosity():
"""
Get the current verbosity level.
Returns:
int: Current verbosity level
"""
def set_verbosity(v):
"""
Set the logging verbosity level.
Args:
v (int): Verbosity level (DEBUG=10, INFO=20, WARNING=30, ERROR=40, FATAL=50)
"""
def set_stderrthreshold(s):
"""
Set the stderr threshold level.
Messages at or above this level will be printed to stderr.
Args:
s (int): Stderr threshold level
"""Functions to check if logging is enabled at specific levels for performance optimization.
def level_debug():
"""
Check if debug level logging is enabled.
Returns:
bool: True if debug logging is enabled
"""
def level_info():
"""
Check if info level logging is enabled.
Returns:
bool: True if info logging is enabled
"""
def level_warning():
"""
Check if warning level logging is enabled.
Returns:
bool: True if warning logging is enabled
"""
def level_error():
"""
Check if error level logging is enabled.
Returns:
bool: True if error logging is enabled
"""Per-file verbose logging system for fine-grained debug output control.
def vlog(level, msg, *args, **kwargs):
"""
Log a verbose message at the specified level.
Verbose logging allows different verbosity levels per source file,
controlled by the --v flag and --vmodule flag.
Args:
level (int): Verbose level (higher numbers = more verbose)
msg (str): Message format string
*args: Arguments for string formatting
**kwargs: Additional logging arguments
"""
def vlog_is_on(level):
"""
Check if verbose logging is enabled at the specified level.
Args:
level (int): Verbose level to check
Returns:
bool: True if verbose logging is enabled at this level
"""Logging functions that only output messages under specific conditions to reduce log spam.
def log_every_n(level, msg, n, *args, use_call_stack=False):
"""
Log a message every N times this function is called.
Args:
level (int): Logging level
msg (str): Message format string
n (int): Log every N calls
*args: Arguments for string formatting
use_call_stack (bool): Use call stack location for counting
"""
def log_every_n_seconds(level, msg, n_seconds, *args, use_call_stack=False):
"""
Log a message at most once every N seconds.
Args:
level (int): Logging level
msg (str): Message format string
n_seconds (float): Minimum time between log messages
*args: Arguments for string formatting
use_call_stack (bool): Use call stack location for timing
"""
def log_first_n(level, msg, n, *args, use_call_stack=False):
"""
Log a message only for the first N times this function is called.
Args:
level (int): Logging level
msg (str): Message format string
n (int): Number of times to log
*args: Arguments for string formatting
use_call_stack (bool): Use call stack location for counting
"""
def log_if(level, msg, condition, *args):
"""
Log a message only if the condition is true.
Args:
level (int): Logging level
msg (str): Message format string
condition (bool): Condition to check
*args: Arguments for string formatting
"""Additional logging utilities for flushing output and internal operations.
def flush():
"""Flush all logging output to ensure messages are written."""
def get_log_file_name(level=INFO):
"""
Get the log file name for the specified level.
Args:
level (int): Logging level
Returns:
str: Log file name or empty string if logging to stderr
"""
def find_log_dir_and_names(program_name=None, log_dir=None):
"""
Find log directory and construct log file names.
Args:
program_name (str): Name of the program (defaults to sys.argv[0])
log_dir (str): Log directory (defaults to /tmp or system temp)
Returns:
tuple: (log_dir, log_name, log_path)
"""
def find_log_dir(log_dir=None):
"""
Find the appropriate log directory.
Args:
log_dir (str): Preferred log directory
Returns:
str: Log directory path
"""
def get_absl_log_prefix(record):
"""
Get the standard absl log prefix for a record.
Args:
record (logging.LogRecord): Log record
Returns:
str: Formatted log prefix
"""
def skip_log_prefix(func):
"""
Decorator to skip log prefix for a function.
Args:
func: Function to decorate
Returns:
Decorated function
"""
def get_absl_logger():
"""
Get the absl logger instance.
Returns:
ABSLLogger: The absl logger
"""
def get_absl_handler():
"""
Get the absl log handler.
Returns:
ABSLHandler: The absl log handler
"""
def use_python_logging(quiet=False):
"""
Configure absl to use Python's standard logging.
Args:
quiet (bool): If True, don't print conversion message
"""
def use_absl_handler():
"""Configure absl to use its own log handler."""Advanced logging classes for custom log handling and formatting.
class ABSLLogger(logging.Logger):
"""
Enhanced logger class with absl-specific functionality.
Extends Python's standard Logger with absl features like
frame skipping and fatal message handling.
"""
def findCaller(self, stack_info=False, stacklevel=1):
"""Find the caller of the logging function."""
def fatal(self, msg, *args, **kwargs):
"""Log a fatal message and exit."""
@classmethod
def register_frame_to_skip(cls, file_name, function_name, line_number=None):
"""
Register a stack frame to skip when finding caller.
Args:
file_name (str): File name to skip
function_name (str): Function name to skip
line_number (int): Optional line number
"""
class ABSLHandler(logging.Handler):
"""
Main absl log handler that manages log output routing.
Routes log messages to appropriate destinations (stderr, files)
based on configuration and integrates with Python logging.
"""
@property
def python_handler(self):
"""Get the underlying Python handler."""
def activate_python_handler(self):
"""Activate the Python logging handler."""
def use_absl_log_file(self, program_name=None, log_dir=None):
"""Configure logging to use absl log files."""
def start_logging_to_file(self, program_name=None, log_dir=None):
"""Start logging to a file."""
class PythonHandler(logging.StreamHandler):
"""
Stream handler with absl-specific enhancements.
Handles log output to streams (stderr, files) with absl
formatting and file rotation capabilities.
"""
def start_logging_to_file(self, program_name=None, log_dir=None):
"""Start logging to a file."""
def use_absl_log_file(self, program_name=None, log_dir=None):
"""Use absl-style log file naming."""
def flush(self):
"""Flush the handler output."""
class PythonFormatter(logging.Formatter):
"""
Custom formatter for absl log messages.
Formats log messages with absl-style prefixes including
severity, timestamp, thread ID, and source location.
"""
def format(self, record):
"""
Format a log record.
Args:
record (logging.LogRecord): Record to format
Returns:
str: Formatted log message
"""Standard logging levels are available as constants:
# Logging level constants (from Python's logging module)
DEBUG = 10
INFO = 20
WARNING = 30
ERROR = 40
FATAL = 50from absl import logging
# Configure logging verbosity
logging.set_verbosity(logging.INFO)
# Basic logging calls
logging.debug('This will not be shown (below INFO level)')
logging.info('Application started')
logging.warning('This is a warning message')
logging.error('An error occurred')
# String formatting
name = 'Alice'
age = 30
logging.info('User %s is %d years old', name, age)from absl import logging
# Check level before expensive operations
if logging.level_debug():
expensive_debug_info = compute_expensive_debug_info()
logging.debug('Debug info: %s', expensive_debug_info)
# Verbose logging with level checking
if logging.vlog_is_on(2):
detailed_state = get_detailed_system_state()
logging.vlog(2, 'System state: %s', detailed_state)from absl import logging
# Log every 100 iterations to avoid log spam
for i in range(1000):
process_item(i)
logging.log_every_n(logging.INFO, 'Processed %d items', 100, i + 1)
# Log at most once per minute
while running:
check_system_health()
logging.log_every_n_seconds(logging.INFO, 'System health check complete', 60)
# Log only first few occurrences
for item in items:
if item.has_warning():
logging.log_first_n(logging.WARNING, 'Item warning: %s', 5, item.warning)from absl import logging
try:
risky_operation()
except Exception as e:
# Log exception with traceback
logging.exception('Operation failed: %s', str(e))
# Or log error without traceback
logging.error('Operation failed: %s', str(e))from absl import app
from absl import flags
from absl import logging
FLAGS = flags.FLAGS
# The logging module automatically defines these flags:
# --v (verbosity level)
# --vmodule (per-module verbosity)
# --logtostderr (log to stderr)
# --alsologtostderr (also log to stderr)
# --log_dir (log directory)
def main(argv):
# Verbosity is automatically configured from flags
logging.info('Application started with verbosity: %d', logging.get_verbosity())
# Verbose logging (controlled by --v flag)
logging.vlog(1, 'Level 1 verbose message')
logging.vlog(2, 'Level 2 verbose message (more detailed)')
if __name__ == '__main__':
app.run(main)from absl import logging
def validate_config(config):
if not config.get('required_field'):
# This will log the error and exit with code 1
logging.fatal('Configuration missing required field: required_field')
# This line will never be reached if the above condition is true
logging.info('Configuration validated successfully')Install with Tessl CLI
npx tessl i tessl/pypi-absl-py