Logging configuration helpers for czitools.
Provides set_logging, a factory function that returns a configured logging.Logger with optional colorised output via colorlog.
Functions:
-
set_logging – Configures a standard Python logger with customizable level and format.
Configures a standard Python logger with customizable level and format.
Parameters:
- (
int, default: INFO ) – Logging level (e.g., logging.INFO, logging.DEBUG, logging.WARNING)
- (
str | None, default: None ) – Custom format string for log messages. If None, uses default format.
- (
bool, default: True ) – Whether to colorize the output (requires colorlog package)
Returns:
-
Logger – logging.Logger: Configured standard Python logger instance.
Source code in czitools/utils/logging_tools.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76 | def set_logging(level: int = logging.INFO, format_string: str | None = None, colorize: bool = True) -> logging.Logger:
"""
Configures a standard Python logger with customizable level and format.
Args:
level: Logging level (e.g., logging.INFO, logging.DEBUG, logging.WARNING)
format_string: Custom format string for log messages. If None, uses default format.
colorize: Whether to colorize the output (requires colorlog package)
Returns:
logging.Logger: Configured standard Python logger instance.
"""
# Create a logger
logger = logging.getLogger("czitools")
# Clear any existing handlers
logger.handlers.clear()
# Set the logging level
logger.setLevel(level)
# Create console handler
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(level)
# Create formatter
if colorize and HAS_COLORLOG:
# Use colorlog for colored output
if format_string is None:
format_string = "%(log_color)s%(asctime)s - %(name)s - %(levelname)s - %(message)s"
formatter = colorlog.ColoredFormatter(
format_string,
log_colors={
"DEBUG": "cyan",
"INFO": "green",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "red,bg_white",
},
)
else:
# Use standard formatter
if format_string is None:
format_string = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
formatter = logging.Formatter(format_string)
# If colorlog is not available but colorize was requested, warn the user
if colorize and not HAS_COLORLOG:
print("Warning: colorlog package not found. Install with 'pip install colorlog' for colored output.")
console_handler.setFormatter(formatter)
# Add handler to logger
logger.addHandler(console_handler)
return logger
|