0
# Colorlog
1
2
A Python logging formatter that adds color support to terminal output by extending the standard logging.Formatter class. Colorlog provides colored logging formatters with ANSI escape code support for terminals and Windows (via colorama integration), making log output more readable and easier to debug.
3
4
## Package Information
5
6
- **Package Name**: colorlog
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install colorlog`
10
- **Python Version**: 3.6+
11
- **Windows Support**: Automatic via colorama
12
13
## Core Imports
14
15
```python
16
import colorlog
17
```
18
19
For basic colored logging:
20
21
```python
22
from colorlog import ColoredFormatter
23
```
24
25
For enhanced logging functions:
26
27
```python
28
from colorlog import basicConfig, getLogger
29
```
30
31
## Basic Usage
32
33
```python
34
import colorlog
35
36
# Quick setup with basicConfig
37
colorlog.basicConfig()
38
logger = colorlog.getLogger('example')
39
40
logger.debug("Debug message")
41
logger.info("Info message")
42
logger.warning("Warning message")
43
logger.error("Error message")
44
logger.critical("Critical message")
45
```
46
47
For more control:
48
49
```python
50
import colorlog
51
import logging
52
53
# Create colored formatter
54
formatter = colorlog.ColoredFormatter(
55
'%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s',
56
datefmt=None,
57
reset=True,
58
log_colors={
59
'DEBUG': 'cyan',
60
'INFO': 'green',
61
'WARNING': 'yellow',
62
'ERROR': 'red',
63
'CRITICAL': 'red,bg_white',
64
},
65
secondary_log_colors={},
66
style='%'
67
)
68
69
# Create handler and logger
70
handler = colorlog.StreamHandler()
71
handler.setFormatter(formatter)
72
73
logger = colorlog.getLogger('example')
74
logger.addHandler(handler)
75
logger.setLevel(logging.DEBUG)
76
```
77
78
## Architecture
79
80
Colorlog extends Python's standard logging system with color support:
81
82
- **ColoredFormatter**: Main formatter class that adds color codes to log messages
83
- **LevelFormatter**: Per-level format string support for different log levels
84
- **Escape Codes**: ANSI color code generation and parsing system
85
- **Wrapper Functions**: Enhanced logging functions with automatic configuration
86
87
The library maintains full compatibility with Python's logging module while adding color capabilities through ANSI escape codes, with automatic Windows support via colorama.
88
89
## Capabilities
90
91
### Colored Formatters
92
93
Core formatting classes that add color support to log messages. The main ColoredFormatter class extends Python's logging.Formatter with ANSI color codes, while LevelFormatter provides per-level formatting.
94
95
```python { .api }
96
class ColoredFormatter(logging.Formatter):
97
def __init__(
98
self,
99
fmt: Optional[str] = None,
100
datefmt: Optional[str] = None,
101
style: str = "%",
102
log_colors: Optional[Dict[str, str]] = None,
103
reset: bool = True,
104
secondary_log_colors: Optional[Dict[str, Dict[str, str]]] = None,
105
validate: bool = True,
106
stream: Optional[IO[str]] = None,
107
no_color: bool = False,
108
force_color: bool = False,
109
defaults: Optional[Dict[str, Any]] = None,
110
): ...
111
112
class LevelFormatter:
113
def __init__(self, fmt: Dict[str, str], **kwargs: Any): ...
114
```
115
116
[Colored Formatters](./formatters.md)
117
118
### Enhanced Logging Functions
119
120
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.
121
122
```python { .api }
123
def basicConfig(
124
style: str = "%",
125
log_colors: Optional[Dict[str, str]] = None,
126
reset: bool = True,
127
secondary_log_colors: Optional[Dict[str, Dict[str, str]]] = None,
128
format: str = "%(log_color)s%(levelname)s%(reset)s:%(name)s:%(message)s",
129
datefmt: Optional[str] = None,
130
**kwargs
131
) -> None: ...
132
133
def debug(msg, *args, **kwargs): ...
134
def info(msg, *args, **kwargs): ...
135
def warning(msg, *args, **kwargs): ...
136
def error(msg, *args, **kwargs): ...
137
def critical(msg, *args, **kwargs): ...
138
def log(level, msg, *args, **kwargs): ...
139
def exception(msg, *args, **kwargs): ...
140
```
141
142
[Enhanced Logging Functions](./logging-functions.md)
143
144
### Color System
145
146
ANSI escape code generation and color parsing system. Provides comprehensive color support including foreground/background colors, text styling, and 256-color terminal support.
147
148
```python { .api }
149
# Available via colorlog.escape_codes submodule
150
def parse_colors(string: str) -> str: ...
151
152
# Color constants and mappings
153
escape_codes: Dict[str, str]
154
default_log_colors: Dict[str, str]
155
```
156
157
[Color System](./colors.md)
158
159
## Types
160
161
```python { .api }
162
# Type aliases for function signatures
163
from typing import IO, Dict, Mapping, Any, Optional
164
165
EscapeCodes = Mapping[str, str]
166
LogColors = Mapping[str, str]
167
SecondaryLogColors = Mapping[str, LogColors]
168
```
169
170
## Constants
171
172
```python { .api }
173
# Log level constants (re-exported from logging)
174
CRITICAL: int
175
DEBUG: int
176
ERROR: int
177
FATAL: int
178
INFO: int
179
NOTSET: int
180
WARN: int
181
WARNING: int
182
183
# Default color mapping
184
default_log_colors: Dict[str, str]
185
```