0
# Enhanced Logging Functions
1
2
Wrapper functions that enhance Python's standard logging functions with automatic configuration and colored output. These functions automatically set up ColoredFormatter when no handlers exist.
3
4
## Capabilities
5
6
### Basic Configuration
7
8
Enhanced version of logging.basicConfig that automatically uses ColoredFormatter.
9
10
```python { .api }
11
def basicConfig(
12
style: str = "%",
13
log_colors: Optional[LogColors] = None,
14
reset: bool = True,
15
secondary_log_colors: Optional[SecondaryLogColors] = None,
16
format: str = "%(log_color)s%(levelname)s%(reset)s:%(name)s:%(message)s",
17
datefmt: Optional[str] = None,
18
**kwargs
19
) -> None:
20
"""
21
Call logging.basicConfig and override the formatter it creates.
22
23
Parameters:
24
- style: Format style ('%', '{', or '$')
25
- log_colors: Mapping of log level names to color names
26
- reset: Implicitly append color reset to all records
27
- secondary_log_colors: Map secondary log_color attributes
28
- format: Log format string with color support
29
- datefmt: Date format string
30
- **kwargs: Additional arguments passed to logging.basicConfig
31
"""
32
```
33
34
**Usage Example:**
35
```python
36
import colorlog
37
38
# Simple setup with defaults
39
colorlog.basicConfig()
40
41
# Custom setup
42
colorlog.basicConfig(
43
format='%(log_color)s%(levelname)-8s%(reset)s %(message)s',
44
log_colors={
45
'DEBUG': 'cyan',
46
'INFO': 'green',
47
'WARNING': 'yellow',
48
'ERROR': 'red',
49
'CRITICAL': 'bold_red',
50
},
51
level=logging.DEBUG
52
)
53
```
54
55
### Enhanced Logging Functions
56
57
Wrapper functions that automatically configure colored logging if no handlers exist.
58
59
```python { .api }
60
def debug(msg, *args, **kwargs):
61
"""
62
Log a message with severity 'DEBUG' on the root logger.
63
Automatically configures colored logging if needed.
64
"""
65
66
def info(msg, *args, **kwargs):
67
"""
68
Log a message with severity 'INFO' on the root logger.
69
Automatically configures colored logging if needed.
70
"""
71
72
def warning(msg, *args, **kwargs):
73
"""
74
Log a message with severity 'WARNING' on the root logger.
75
Automatically configures colored logging if needed.
76
"""
77
78
def error(msg, *args, **kwargs):
79
"""
80
Log a message with severity 'ERROR' on the root logger.
81
Automatically configures colored logging if needed.
82
"""
83
84
def critical(msg, *args, **kwargs):
85
"""
86
Log a message with severity 'CRITICAL' on the root logger.
87
Automatically configures colored logging if needed.
88
"""
89
90
def log(level, msg, *args, **kwargs):
91
"""
92
Log 'msg % args' with the integer severity 'level' on the root logger.
93
Automatically configures colored logging if needed.
94
"""
95
96
def exception(msg, *args, **kwargs):
97
"""
98
Log a message with severity 'ERROR' on the root logger, with exc_info
99
which is used to include the current exception in the log message.
100
Automatically configures colored logging if needed.
101
"""
102
```
103
104
**Usage Example:**
105
```python
106
import colorlog
107
108
# These functions will automatically set up colored logging
109
colorlog.debug("Debug message")
110
colorlog.info("Info message")
111
colorlog.warning("Warning message")
112
colorlog.error("Error message")
113
colorlog.critical("Critical message")
114
115
# Log with custom level
116
colorlog.log(25, "Custom level message")
117
118
# Log exception with traceback
119
try:
120
1 / 0
121
except:
122
colorlog.exception("An error occurred")
123
```
124
125
### Re-exported Logging Objects
126
127
Standard logging objects re-exported for convenience.
128
129
```python { .api }
130
# Logger creation and management
131
def getLogger(name: Optional[str] = None) -> logging.Logger:
132
"""Return a logger with the specified name or root logger if None."""
133
134
# Handler class
135
class StreamHandler(logging.StreamHandler):
136
"""Stream handler for logging output."""
137
138
# Root logger instance
139
root: logging.Logger
140
```
141
142
**Usage Example:**
143
```python
144
import colorlog
145
146
# Get a named logger
147
logger = colorlog.getLogger('myapp')
148
149
# Use StreamHandler directly
150
handler = colorlog.StreamHandler()
151
formatter = colorlog.ColoredFormatter()
152
handler.setFormatter(formatter)
153
logger.addHandler(handler)
154
155
# Access root logger
156
colorlog.root.setLevel(logging.DEBUG)
157
```
158
159
### Log Level Constants
160
161
Standard logging level constants re-exported for convenience.
162
163
```python { .api }
164
# Log level constants
165
CRITICAL: int # 50
166
DEBUG: int # 10
167
ERROR: int # 40
168
FATAL: int # 50 (alias for CRITICAL)
169
INFO: int # 20
170
NOTSET: int # 0
171
WARN: int # 30 (deprecated alias for WARNING)
172
WARNING: int # 30
173
```
174
175
**Usage Example:**
176
```python
177
import colorlog
178
179
# Set log levels using constants
180
logger = colorlog.getLogger('example')
181
logger.setLevel(colorlog.DEBUG)
182
183
# Use in conditional logging
184
if logger.isEnabledFor(colorlog.WARNING):
185
logger.warning("This is a warning")
186
```
187
188
## Automatic Configuration
189
190
The enhanced logging functions use a decorator that automatically calls `basicConfig()` with default colored formatting if no handlers exist on the root logger. This provides immediate colored output without manual setup.
191
192
**Internal Implementation:**
193
```python
194
def ensure_configured(func):
195
"""Modify a function to call basicConfig() first if no handlers exist."""
196
@functools.wraps(func)
197
def wrapper(*args, **kwargs):
198
if len(logging.root.handlers) == 0:
199
basicConfig()
200
return func(*args, **kwargs)
201
return wrapper
202
```
203
204
This ensures that colorlog functions work out-of-the-box while maintaining compatibility with existing logging configurations.
205
206
## Configuration Methods
207
208
### Dictionary Configuration
209
210
```python
211
import logging.config
212
213
logging.config.dictConfig({
214
'formatters': {
215
'colored': {
216
'()': 'colorlog.ColoredFormatter',
217
'format': "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s"
218
}
219
},
220
'handlers': {
221
'console': {
222
'class': 'logging.StreamHandler',
223
'formatter': 'colored'
224
}
225
},
226
'root': {
227
'handlers': ['console'],
228
'level': 'DEBUG'
229
}
230
})
231
```
232
233
### File Configuration
234
235
```ini
236
[formatters]
237
keys=color
238
239
[formatter_color]
240
class=colorlog.ColoredFormatter
241
format=%(log_color)s%(levelname)-8s%(reset)s %(bg_blue)s[%(name)s]%(reset)s %(message)s
242
datefmt=%m-%d %H:%M:%S
243
```