0
# Color System
1
2
ANSI escape code generation and color parsing system. Provides comprehensive color support including foreground/background colors, text styling, and 256-color terminal support.
3
4
## Capabilities
5
6
### Color Parsing
7
8
Parse comma-separated color sequence strings into ANSI escape codes.
9
10
```python { .api }
11
# Import from colorlog.escape_codes module
12
from colorlog.escape_codes import parse_colors
13
14
def parse_colors(string: str) -> str:
15
"""
16
Return escape codes from a color sequence string.
17
18
Parameters:
19
- string: Comma-separated color names (e.g., "red,bold" or "blue,bg_white")
20
21
Returns:
22
- str: Combined ANSI escape codes
23
"""
24
```
25
26
**Usage Example:**
27
```python
28
from colorlog.escape_codes import parse_colors
29
30
# Parse single color
31
red_code = parse_colors("red")
32
print(f"{red_code}This is red text\033[0m")
33
34
# Parse multiple colors
35
bold_red_on_white = parse_colors("bold_red,bg_white")
36
print(f"{bold_red_on_white}Bold red text on white background\033[0m")
37
38
# Parse complex combinations
39
style = parse_colors("bold,blue,bg_yellow")
40
print(f"{style}Bold blue text on yellow background\033[0m")
41
```
42
43
### Escape Codes Dictionary
44
45
Complete mapping of color names to ANSI escape codes.
46
47
```python { .api }
48
# Import from colorlog.escape_codes module
49
from colorlog.escape_codes import escape_codes
50
from typing import Dict
51
52
escape_codes: Dict[str, str]
53
```
54
55
The `escape_codes` dictionary contains all available color and formatting codes:
56
57
**Basic Formatting:**
58
- `reset`: Clear all formatting
59
- `bold`: Bold/bright text
60
- `thin`: Thin text (terminal dependent)
61
62
**Foreground Colors:**
63
- Basic colors: `black`, `red`, `green`, `yellow`, `blue`, `purple`, `cyan`, `white`
64
- Light colors: `light_black`, `light_red`, `light_green`, `light_yellow`, `light_blue`, `light_purple`, `light_cyan`, `light_white`
65
- With bold: `bold_black`, `bold_red`, etc.
66
- With thin: `thin_black`, `thin_red`, etc.
67
- With prefix: `fg_black`, `fg_red`, etc.
68
69
**Background Colors:**
70
- Basic: `bg_black`, `bg_red`, `bg_green`, `bg_yellow`, `bg_blue`, `bg_purple`, `bg_cyan`, `bg_white`
71
- Light: `bg_light_black`, `bg_light_red`, etc.
72
73
**256-Color Support:**
74
- Foreground: `fg_0` through `fg_255`
75
- Background: `bg_0` through `bg_255`
76
77
**Usage Example:**
78
```python
79
from colorlog.escape_codes import escape_codes
80
81
# Access individual escape codes
82
print(f"{escape_codes['red']}Red text{escape_codes['reset']}")
83
print(f"{escape_codes['bold_blue']}Bold blue text{escape_codes['reset']}")
84
print(f"{escape_codes['bg_yellow']}Yellow background{escape_codes['reset']}")
85
86
# 256-color support
87
print(f"{escape_codes['fg_196']}Bright red (256-color){escape_codes['reset']}")
88
print(f"{escape_codes['bg_21']}Blue background (256-color){escape_codes['reset']}")
89
```
90
91
### Default Log Colors
92
93
Default color mapping for log levels used by ColoredFormatter.
94
95
```python { .api }
96
# Import from colorlog.formatter module
97
from colorlog.formatter import default_log_colors
98
from typing import Dict
99
100
default_log_colors: Dict[str, str] = {
101
"DEBUG": "white",
102
"INFO": "green",
103
"WARNING": "yellow",
104
"ERROR": "red",
105
"CRITICAL": "bold_red",
106
}
107
```
108
109
**Usage Example:**
110
```python
111
from colorlog.formatter import default_log_colors
112
import colorlog
113
114
# Use default colors
115
formatter = colorlog.ColoredFormatter(
116
log_colors=default_log_colors
117
)
118
119
# Customize based on defaults
120
custom_colors = default_log_colors.copy()
121
custom_colors["DEBUG"] = "cyan"
122
custom_colors["CRITICAL"] = "red,bg_white"
123
124
formatter = colorlog.ColoredFormatter(log_colors=custom_colors)
125
```
126
127
## Color Names Reference
128
129
### Standard Colors
130
131
**Basic Colors:**
132
- `black`, `red`, `green`, `yellow`, `blue`, `purple`, `cyan`, `white`
133
134
**Light/Bright Colors:**
135
- `light_black`, `light_red`, `light_green`, `light_yellow`
136
- `light_blue`, `light_purple`, `light_cyan`, `light_white`
137
138
### Color Combinations
139
140
Colors can be combined with commas in color specifications:
141
142
```python
143
# Multiple effects
144
"bold,red" # Bold red text
145
"red,bg_white" # Red text on white background
146
"bold,blue,bg_yellow" # Bold blue text on yellow background
147
"thin,green" # Thin green text
148
```
149
150
### Format Styles
151
152
Colors work with all Python logging format styles:
153
154
**Percent Style (%):**
155
```python
156
"%(log_color)s%(levelname)s%(reset)s: %(message)s"
157
```
158
159
**Brace Style ({}):**
160
```python
161
"{log_color}{levelname}{reset}: {message}"
162
```
163
164
**Dollar Style ($):**
165
```python
166
"${log_color}${levelname}${reset}: ${message}"
167
```
168
169
## Platform Support
170
171
### Windows Support
172
173
Colorlog automatically detects Windows and initializes colorama for ANSI color support:
174
175
```python
176
# Automatic Windows setup (internal)
177
import sys
178
try:
179
import colorama
180
except ImportError:
181
pass
182
else:
183
if sys.platform == "win32":
184
colorama.init(strip=False)
185
```
186
187
### Terminal Detection
188
189
Colors are automatically disabled for non-TTY streams unless forced:
190
191
```python
192
formatter = colorlog.ColoredFormatter(
193
stream=sys.stdout, # TTY detection
194
no_color=False, # Respect NO_COLOR env var
195
force_color=False # Force colors regardless of TTY
196
)
197
```
198
199
### Environment Variables
200
201
- **NO_COLOR**: Disable color output when set
202
- **FORCE_COLOR**: Force color output when set (overrides NO_COLOR)
203
204
## Internal Color Generation
205
206
The escape codes are generated programmatically using internal helper functions:
207
208
```python { .api }
209
# Internal helper function (from colorlog.escape_codes module)
210
def esc(*codes: int) -> str:
211
"""
212
Generate ANSI escape sequence from numeric codes.
213
214
Parameters:
215
- codes: Variable number of ANSI numeric codes
216
217
Returns:
218
- str: Complete ANSI escape sequence
219
"""
220
return "\033[" + ";".join(str(code) for code in codes) + "m"
221
222
# Internal color code dictionaries
223
escape_codes_foreground: Dict[str, int]
224
escape_codes_background: Dict[str, int]
225
```
226
227
**Usage Example:**
228
```python
229
from colorlog.escape_codes import esc
230
231
# Generate custom escape codes
232
red_code = esc(31) # \033[31m
233
bold_red_code = esc(1, 31) # \033[1;31m
234
bg_red_code = esc(41) # \033[41m
235
```
236
237
This ensures consistent ANSI escape code generation across all supported colors and styles.