Your goto Python logging without panic on context switch
npx @tessl/cli install tessl/pypi-alog@1.2.00
# Alog
1
2
Your goto Python logging without panic on context switch. Alog is a simplified Python logging library that provides instant logging capabilities with sensible defaults, eliminating the need for manual logger setup and configuration in each module.
3
4
## Package Information
5
6
- **Package Name**: alog
7
- **Language**: Python
8
- **Installation**: `pip install alog`
9
10
## Core Imports
11
12
```python
13
import alog
14
```
15
16
For accessing specific logging levels:
17
18
```python
19
from alog import INFO, ERROR, WARNING, DEBUG, CRITICAL
20
```
21
22
For advanced usage with custom loggers:
23
24
```python
25
from alog import Alogger, init_alogger, default_alog_config, StreamHandler
26
```
27
28
## Basic Usage
29
30
```python
31
import alog
32
33
# Simple logging - no setup required
34
alog.info("Application started")
35
alog.error("Something went wrong")
36
alog.debug("Debug information")
37
38
# Pretty print complex objects
39
data = {"users": [1, 2, 3], "status": "active"}
40
alog.info(alog.pformat(data))
41
42
# Inspect object attributes
43
class MyClass:
44
def __init__(self):
45
self.public_attr = "visible"
46
self._private_attr = "hidden"
47
48
obj = MyClass()
49
alog.info(alog.pdir(obj)) # Shows only public attributes
50
51
# Configure logging behavior
52
alog.set_level("DEBUG")
53
alog.turn_logging_datetime(on=True)
54
alog.turn_logging_thread_name(on=True)
55
alog.turn_logging_process_id(on=True)
56
```
57
58
## Architecture
59
60
Alog is built on Python's standard logging module with these key components:
61
62
- **Global Default Logger**: Pre-configured logger accessible through module-level functions
63
- **Alogger Class**: Enhanced Logger subclass with context-aware path formatting
64
- **Configuration System**: Simple API for customizing output formats and behavior
65
- **Utility Functions**: Built-in pretty printing and object inspection capabilities
66
67
The library automatically detects module names and formats log messages with clean, readable output showing file paths and line numbers without requiring manual logger initialization.
68
69
## Capabilities
70
71
### Basic Logging Functions
72
73
Standard logging functions that work out-of-the-box without any configuration.
74
75
```python { .api }
76
def critical(msg, *args, **kwargs):
77
"""Log a message with severity 'CRITICAL'."""
78
79
def fatal(msg, *args, **kwargs):
80
"""Log a message with severity 'CRITICAL' (alias for critical)."""
81
82
def error(msg, *args, **kwargs):
83
"""Log a message with severity 'ERROR'."""
84
85
def exception(msg, *args, exc_info=None, **kwargs):
86
"""Log a message with severity 'ERROR', with exception info."""
87
88
def warning(msg, *args, **kwargs):
89
"""Log a message with severity 'WARNING'."""
90
91
def warn(msg, *args, **kwargs):
92
"""Log a message with severity 'WARNING' (alias for warning)."""
93
94
def info(msg, *args, **kwargs):
95
"""Log a message with severity 'INFO'."""
96
97
def debug(msg, *args, **kwargs):
98
"""Log a message with severity 'DEBUG'."""
99
100
def log(level, msg, *args, **kwargs):
101
"""Log 'msg % args' with the specified severity 'level'."""
102
```
103
104
### Configuration Functions
105
106
Control logging behavior and output formatting.
107
108
```python { .api }
109
def set_level(level, alogger=None):
110
"""
111
Set the effective level for logging.
112
113
Parameters:
114
- level: int or str, logging level (e.g., 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
115
- alogger: Alogger instance, optional (defaults to global logger)
116
"""
117
118
def get_level(alogger=None):
119
"""
120
Get the effective level for logging.
121
122
Parameters:
123
- alogger: Alogger instance, optional (defaults to global logger)
124
125
Returns:
126
int | None: Current logging level from handlers, or None if no level set
127
"""
128
129
def turn_logging_datetime(on, alogger=None):
130
"""
131
Enable or disable datetime in log output.
132
133
Parameters:
134
- on: bool, whether to show datetime
135
- alogger: Alogger instance, optional (defaults to global logger)
136
"""
137
138
def turn_logging_thread_name(on, alogger=None):
139
"""
140
Enable or disable thread name in log output.
141
142
Parameters:
143
- on: bool, whether to show thread name
144
- alogger: Alogger instance, optional (defaults to global logger)
145
"""
146
147
def turn_logging_process_id(on, alogger=None):
148
"""
149
Enable or disable process ID in log output.
150
151
Parameters:
152
- on: bool, whether to show process ID
153
- alogger: Alogger instance, optional (defaults to global logger)
154
"""
155
156
def disable(level, alogger=None):
157
"""
158
Disable logging calls of specified severity 'level' and below.
159
160
Parameters:
161
- level: int or str, logging level to disable
162
- alogger: Alogger instance, optional (defaults to global logger)
163
"""
164
```
165
166
### Formatting Functions
167
168
Customize log output formatting and appearance.
169
170
```python { .api }
171
def set_format(fs, alogger=None, is_default=False, time_strfmt="%Y-%m-%d %H:%M:%S"):
172
"""
173
Set the format string for log output.
174
175
Parameters:
176
- fs: str, format string for log messages
177
- alogger: Alogger instance, optional (defaults to global logger)
178
- is_default: bool, whether this is a default format
179
- time_strfmt: str, datetime format string
180
"""
181
182
def get_format(alogger=None):
183
"""
184
Get the current format (deprecated, use get_formatter).
185
186
Parameters:
187
- alogger: Alogger instance, optional (defaults to global logger)
188
189
Returns:
190
Formatter: Current formatter object
191
"""
192
193
def set_formatter(formatter, alogger=None):
194
"""
195
Set a custom formatter object.
196
197
Parameters:
198
- formatter: logging.Formatter instance
199
- alogger: Alogger instance, optional (defaults to global logger)
200
"""
201
202
def get_formatter(alogger=None):
203
"""
204
Get the current formatter object.
205
206
Parameters:
207
- alogger: Alogger instance, optional (defaults to global logger)
208
209
Returns:
210
logging.Formatter: Current formatter
211
"""
212
213
def set_root_name(root_name, alogger=None):
214
"""
215
Set the root name for path formatting.
216
217
Parameters:
218
- root_name: str, root directory name for path display
219
- alogger: Alogger instance, optional (defaults to global logger)
220
"""
221
```
222
223
### Utility Functions
224
225
Built-in utilities for pretty printing and object inspection.
226
227
```python { .api }
228
def pformat(*args, **kwargs):
229
"""
230
Pretty format objects using pprint with newline prefix.
231
232
Parameters:
233
- *args: objects to format
234
- **kwargs: options passed to pprint.pformat
235
236
Returns:
237
str: Pretty formatted string with leading newline
238
"""
239
240
def pdir(obj, str_not_startswith="_"):
241
"""
242
Pretty format object directory, filtering attributes by prefix.
243
244
Parameters:
245
- obj: object to inspect
246
- str_not_startswith: str, filter out attributes starting with this string
247
248
Returns:
249
str: Pretty formatted list of object attributes
250
"""
251
```
252
253
### Logger Management Functions
254
255
Advanced functions for managing logger instances and configuration.
256
257
```python { .api }
258
def getLogger(*args, **kwargs):
259
"""
260
Get the default logger (ignores arguments, shows warning if provided).
261
262
Returns:
263
Alogger: The default global logger instance
264
"""
265
266
def init_alogger(alog_config, default_root_name=None):
267
"""
268
Initialize a new Alogger instance with configuration.
269
270
Parameters:
271
- alog_config: dict, configuration dictionary
272
- default_root_name: str, optional root name for path formatting
273
274
Returns:
275
Alogger: Configured logger instance
276
"""
277
278
def default_alog_config():
279
"""
280
Get the default alog configuration dictionary.
281
282
Returns:
283
dict: Default configuration with format strings and options
284
"""
285
286
def reset_global_alog():
287
"""
288
Reset the global alog configuration and default logger.
289
"""
290
```
291
292
### Advanced Alogger Class
293
294
For users who need direct access to the underlying logger class.
295
296
```python { .api }
297
class Alogger:
298
"""
299
Enhanced Logger subclass with context-aware formatting and convenience methods.
300
"""
301
302
def __init__(self, root_name, *args, **kwargs):
303
"""
304
Initialize Alogger instance.
305
306
Parameters:
307
- root_name: str, root name for path formatting
308
- *args: additional arguments passed to Logger
309
- **kwargs: additional keyword arguments passed to Logger
310
"""
311
312
def set_level(self, level, logger=None):
313
"""Set logging level for this logger and its handlers."""
314
315
def get_level(self, logger=None):
316
"""Get logging level from handlers."""
317
318
def set_formatter(self, formatter, alogger=None):
319
"""Set formatter for all handlers."""
320
321
def set_format(self, fs, alogger=None, is_default=False, time_strfmt="%Y-%m-%d %H:%M:%S"):
322
"""Set format string for all handlers."""
323
324
def get_formatter(self, logger=None):
325
"""Get formatter from handlers."""
326
327
def get_format(self, logger=None):
328
"""Get format (deprecated, use get_formatter)."""
329
330
def set_root_name(self, root_name, logger=None):
331
"""Set root name for path formatting."""
332
333
def turn_logging_datetime(self, on):
334
"""Enable/disable datetime in log output."""
335
336
def turn_logging_thread_name(self, on):
337
"""Enable/disable thread name in log output."""
338
339
def turn_logging_process_id(self, on):
340
"""Enable/disable process ID in log output."""
341
342
def disable(self, level):
343
"""Disable logging at specified level."""
344
345
@staticmethod
346
def pformat(*args, **kwargs):
347
"""Pretty format objects using pprint with newline prefix."""
348
349
@classmethod
350
def pdir(cls, obj, str_not_startswith="_"):
351
"""Pretty format object directory, filtering by prefix."""
352
```
353
354
## Constants
355
356
Logging level constants imported from Python's logging module.
357
358
```python { .api }
359
CRITICAL: int = 50
360
ERROR: int = 40
361
WARNING: int = 30
362
INFO: int = 20
363
DEBUG: int = 10
364
365
# Note: FATAL is an alias for CRITICAL
366
fatal = critical # Function alias
367
```
368
369
## Module Variables
370
371
Global objects available after import.
372
373
```python { .api }
374
default_logger: Alogger # The global default logger instance
375
config: dict # Global configuration dictionary
376
StreamHandler: type # Stream handler class from logging module
377
```
378
379
## Usage Examples
380
381
### Simple Logging
382
383
```python
384
import alog
385
386
alog.info("Application started")
387
alog.warning("This is a warning")
388
alog.error("An error occurred")
389
```
390
391
### Configuration
392
393
```python
394
import alog
395
396
# Set logging level
397
alog.set_level("DEBUG")
398
399
# Enable datetime and thread info
400
alog.turn_logging_datetime(on=True)
401
alog.turn_logging_thread_name(on=True)
402
403
# Custom format
404
alog.set_format("%(asctime)s [%(levelname)s] %(message)s")
405
406
alog.info("Configured logging message")
407
```
408
409
### Pretty Printing
410
411
```python
412
import alog
413
414
# Pretty print complex data structures
415
data = {
416
"users": ["alice", "bob", "charlie"],
417
"config": {"debug": True, "timeout": 30},
418
"metrics": [1.5, 2.3, 4.7, 1.2]
419
}
420
421
alog.info("Application data:" + alog.pformat(data))
422
423
# Inspect object attributes
424
class DatabaseConnection:
425
def __init__(self):
426
self.host = "localhost"
427
self.port = 5432
428
self._password = "secret" # Won't be shown
429
430
db = DatabaseConnection()
431
alog.info("DB connection attributes:" + alog.pdir(db))
432
```
433
434
### Custom Logger Instances
435
436
```python
437
import alog
438
from alog import StreamHandler
439
440
# Create custom logger with specific configuration
441
config = alog.default_alog_config()
442
config['showing_thread_name'] = True
443
444
custom_logger = alog.init_alogger(config, "myapp")
445
custom_logger.info("Message from custom logger")
446
447
# Direct Alogger usage with custom handler
448
from alog import Alogger
449
450
app_logger = Alogger("myapp")
451
handler = StreamHandler()
452
app_logger.addHandler(handler)
453
app_logger.info("Direct Alogger usage")
454
```