0
# Console Logging
1
2
Configurable console output system with colored labels, timestamps, and themed formatting. Supports both simple and powerline display themes with extensive customization through YAML configuration.
3
4
## Capabilities
5
6
### Main Logging Functions
7
8
Core logging functions available at the package level, providing convenient access to themed console output.
9
10
```python { .api }
11
def log(*args, **kwargs):
12
"""
13
General logging function with optional labels and timestamps.
14
15
Args:
16
*args: Content to log
17
**kwargs: Options including time, info, warn, error, success flags
18
"""
19
20
def info(*args):
21
"""
22
Info-level logging with INFO label.
23
24
Args:
25
*args: Content to log
26
"""
27
28
def warn(*args):
29
"""
30
Warning-level logging with WARNING label.
31
32
Args:
33
*args: Content to log
34
"""
35
36
def error(*args):
37
"""
38
Error-level logging with ERROR label.
39
40
Args:
41
*args: Content to log
42
"""
43
44
def success(*args):
45
"""
46
Success-level logging with SUCCESS label.
47
48
Args:
49
*args: Content to log
50
"""
51
```
52
53
### Console Objects
54
55
Direct access to console instances for advanced usage and custom formatting.
56
57
```python { .api }
58
console: SimpleConsole | PowerlineConsole
59
"""
60
Global console instance (type depends on theme configuration).
61
Can be called directly: console('message')
62
"""
63
```
64
65
### Configuration Management
66
67
Configuration system for customizing colors, labels, and console behavior.
68
69
```python { .api }
70
class Config:
71
"""
72
Configuration management class for hues settings.
73
74
Args:
75
force_default (bool): Use only default config, ignore user configs
76
"""
77
def __init__(self, force_default: bool = False): ...
78
79
@staticmethod
80
def load_config(force_default: bool = False) -> dict:
81
"""
82
Load configuration from .hues.yml files.
83
84
Args:
85
force_default (bool): Use only package defaults
86
87
Returns:
88
dict: Merged configuration
89
"""
90
91
def resolve_config(self) -> None:
92
"""Resolve configuration to namedtuples."""
93
94
# Configuration properties
95
hues: object # Color mappings namedtuple
96
opts: object # Options namedtuple
97
labels: object # Labels namedtuple
98
```
99
100
### Console Classes
101
102
Direct console classes for custom implementations. These are imported internally but can be accessed directly if needed.
103
104
```python { .api }
105
class SimpleConsole:
106
"""
107
Basic console with colored labels and separators.
108
109
Args:
110
conf (Config, optional): Configuration object
111
stdout: Output stream (default: sys.stdout)
112
"""
113
def __init__(self, conf: Config = None, stdout = None): ...
114
115
def log(self, *args, **kwargs): ...
116
def info(self, *args): ...
117
def warn(self, *args): ...
118
def error(self, *args): ...
119
def success(self, *args): ...
120
def __call__(self, *args): ...
121
122
class PowerlineConsole(SimpleConsole):
123
"""
124
Enhanced console with powerline-style connected segments.
125
126
Args:
127
conf (Config, optional): Configuration object
128
stdout: Output stream (default: sys.stdout)
129
"""
130
def __init__(self, conf: Config = None, stdout = None): ...
131
# Inherits all methods from SimpleConsole
132
```
133
134
### Exception Classes
135
136
```python { .api }
137
class InvalidConfiguration(Exception):
138
"""Raised when configuration file is invalid."""
139
```
140
141
## Usage Examples
142
143
### Basic Logging
144
```python
145
import hues
146
147
# Simple logging with labels
148
hues.info('Application started')
149
hues.warn('Low memory warning')
150
hues.error('Connection failed')
151
hues.success('Task completed')
152
153
# General logging with custom options
154
hues.log('Custom message', time=True, info=True)
155
```
156
157
### Advanced Logging
158
```python
159
# Direct console usage
160
hues.console('Plain message')
161
hues.console(('Colored', hues.console.conf.hues.success), 'and plain text')
162
163
# Multiple content with colors
164
hues.console(
165
('Step 1', hues.console.conf.hues.info),
166
('Completed', hues.console.conf.hues.success)
167
)
168
```
169
170
### Custom Console
171
```python
172
from hues.console import Config, SimpleConsole, PowerlineConsole
173
174
# Custom configuration
175
config = Config(force_default=True)
176
177
# Custom console instance
178
console = SimpleConsole(conf=config)
179
console.info('Custom console message')
180
181
# Powerline console
182
powerline = PowerlineConsole(conf=config)
183
powerline.success('Powerline style message')
184
```
185
186
## Configuration System
187
188
### Configuration Loading Order
189
1. Package defaults (hues/.hues.yml)
190
2. User home directory (~/.hues.yml)
191
3. Current working directory (.hues.yml, searched recursively up to root)
192
193
Later configurations override earlier ones using deep dictionary merging.
194
195
### Configuration Structure
196
197
```yaml
198
hues:
199
default: defaultfg # Default text color
200
time: magenta # Timestamp color
201
label: blue # General label color
202
info: cyan # Info label color
203
success: green # Success label color
204
error: red # Error label color
205
warn: yellow # Warning label color
206
207
labels:
208
info: INFO # Info label text
209
warn: WARNING # Warning label text
210
error: ERROR # Error label text
211
success: SUCCESS # Success label text
212
213
options:
214
show_time: yes # Show timestamps by default
215
time_format: '%H:%M:%S' # Timestamp format
216
add_newline: yes # Add newline after each message
217
theme: simple # Console theme: 'simple' or 'powerline'
218
```
219
220
### Theme Differences
221
222
**Simple Theme**: Basic colored labels with dash separators
223
```
224
[12:34:56] INFO - Application started
225
[12:34:56] WARNING - Low disk space
226
```
227
228
**Powerline Theme**: Connected segments with background colors and arrows
229
```
230
12:34:56 INFO Application started
231
12:34:56 WARNING Low disk space
232
```
233
234
## Log Message Formatting
235
236
### Content Processing
237
- Multiple arguments are joined with spaces
238
- Tuples of (content, color) are rendered with specified colors
239
- Colors are resolved from configuration or direct color codes
240
- Time stamps are automatically formatted and colored
241
242
### Label Behavior
243
- Labels are added based on method called (info, warn, error, success)
244
- `log()` method can add labels via keyword arguments
245
- Each label has configurable text and color from configuration
246
- Labels are separated from content with dashes (simple) or styling (powerline)
247
248
## Advanced Usage
249
250
### Configuration File Resolution
251
252
The configuration loading process follows a specific hierarchy with deep merging:
253
254
```python
255
from hues.console import Config
256
257
# Force use of defaults only (ignore user configs)
258
config = Config(force_default=True)
259
260
# Load with full hierarchy (default behavior)
261
config = Config()
262
263
# Access resolved configuration
264
print(config.hues.info) # Color code for info messages
265
print(config.labels.info) # Label text for info messages
266
print(config.opts.theme) # Active theme name
267
```
268
269
### Custom Output Streams
270
271
Console classes support custom output streams for testing or redirection:
272
273
```python
274
import io
275
from hues.console import SimpleConsole, Config
276
277
# Redirect to string buffer
278
buffer = io.StringIO()
279
console = SimpleConsole(stdout=buffer)
280
console.info('Test message')
281
282
# Get output
283
output = buffer.getvalue()
284
print(repr(output)) # Includes ANSI codes
285
```
286
287
### Raw Logging Interface
288
289
Direct access to internal logging methods for custom formatting:
290
291
```python
292
from hues import console
293
from hues.huestr import HueString
294
295
# Build custom colored components
296
time_component = HueString('12:34:56', hue_stack=(console.conf.hues.time,))
297
label_component = HueString('CUSTOM', hue_stack=(console.conf.hues.success,))
298
content_component = HueString('Message text', hue_stack=(console.conf.hues.default,))
299
300
# Use raw logging
301
console._raw_log(time_component, label_component, content_component)
302
```
303
304
### Exception Handling
305
306
Configuration errors are handled with specific exceptions:
307
308
```python
309
from hues.console import Config, InvalidConfiguration
310
311
try:
312
config = Config()
313
except InvalidConfiguration as e:
314
print(f"Config error: {e}")
315
# Falls back to default configuration
316
```
317
318
Common causes of InvalidConfiguration:
319
- Malformed YAML syntax in .hues.yml files
320
- Configuration root is not a dictionary
321
- Invalid color names in hues section
322
323
### Powerline Theme Implementation
324
325
The PowerlineConsole uses background colors and Unicode arrows for connected segments:
326
327
- Text is rendered with background colors matching the segment color
328
- Foreground color is automatically chosen (black/white) based on background brightness
329
- Arrow characters (►) connect segments using foreground colors
330
- Final segment ends without an arrow
331
332
### Internal Configuration Structure
333
334
After loading, configuration is converted to namedtuples for efficient access:
335
336
```python
337
# Configuration structure after resolve_config()
338
config.hues # Namedtuple with color codes (not names)
339
config.labels # Namedtuple with label text strings
340
config.opts # Namedtuple with boolean/string options
341
```
342
343
This allows dot notation access while preventing accidental modification of the configuration during runtime.