Reference¶
dsg_lib.common_functions.logging_config
¶
This module provides a comprehensive logging setup using the loguru library, facilitating easy logging management for Python applications.
The config_log function, central to this module, allows for extensive customization of logging behavior. It supports specifying the logging directory, log file name, logging level, and controls for log rotation, retention, and formatting among other features. Additionally, it offers advanced options like backtrace and diagnose for in-depth debugging, the ability to append the application name to the log file for clearer identification, and control over logger propagation via the log_propagate parameter.
Usage example:
from dsg_lib.common_functions.logging_config import config_log
config_log(
logging_directory='logs', # Directory for storing logs
log_name='log', # Base name for log files
logging_level='DEBUG', # Minimum logging level
log_rotation='100 MB', # Size threshold for log rotation
log_retention='30 days', # Duration to retain old log files
log_propagate=False, # Control log propagation
)
# Example log messages
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.error("This is an error message")
logger.warning("This is a warning message")
logger.critical("This is a critical message")
Performance notes
Logging runs on the host application's request path, so the defaults are chosen for low per-message cost:
- The file sink keeps one open handle and checks the file size with
os.fstaton that handle, instead of opening, closing and stat-ing the file for every message. - Rotated files are compressed on a background thread, so a rotation never blocks the thread that logged.
enqueuedefaults toFalse. loguru's queue pickles every message through a multiprocessing pipe, which costs several times more than the write itself. Opt in withenqueue=Trueif you need the write fully off the calling thread.- With
intercept_standard_logging=True, the stdlib root logger is set tointercept_level(defaults tologging_level), so stdlib records below that level are rejected before aLogRecordis even built. log_to_file=False, log_to_stdout=Trueskips the file sink entirely, which suits containers that ship stdout.
Date Created
2021/07/16
Date Updated
2026/10/24
License
MIT
InterceptHandler
¶
Bases: Handler
A logging handler that intercepts standard logging messages and redirects them to Loguru.
This handler captures log messages from the standard logging module and forwards them to Loguru, preserving the log level and message details.
Methods:
| Name | Description |
|---|---|
emit |
Emits a log record to Loguru. |
Source code in dsg_lib/common_functions/logging_config.py
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 | |
emit(record)
¶
Emits a log record to Loguru.
This method captures the log record, determines the appropriate Loguru log level, and logs the message using Loguru. It also handles exceptions and finds the caller's frame to maintain accurate log information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
LogRecord
|
The log record to be emitted. |
required |
Returns:
| Type | Description |
|---|---|
|
None |
Source code in dsg_lib/common_functions/logging_config.py
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 | |
SafeFileSink
¶
A loguru file sink with size-based rotation, age-based retention and optional compression, safe for several processes writing one file.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The path to the log file. |
rotation_size |
int
|
The size threshold for log rotation in bytes. |
retention_days |
timedelta
|
The duration to retain old log files. |
compression |
str
|
The |
retention_check_interval |
float
|
Minimum seconds between retention sweeps (see note below). |
reopen_check_interval |
float
|
Minimum seconds between checks that the
open handle still points at |
compress_in_background |
bool
|
Compress rotated files on a background thread instead of on the thread that logged. |
Methods:
| Name | Description |
|---|---|
parse_size |
Parses a size string (e.g., '100MB') and returns the size in bytes. |
parse_duration |
Parses a duration string (e.g., '7 days') and returns a timedelta object. |
write |
Write one formatted message (loguru calls this). |
stop |
Wait for background compression and close the file. |
Note on the hot path
Each message costs one buffered write, one flush and one os.fstat on
the already-open descriptor. fstat on the descriptor also sees bytes
appended by other processes sharing the file, which an in-memory byte
counter would miss.
Note on multiple processes
Forked workers append to the same file; O_APPEND keeps their lines
from interleaving. When one worker rotates, the others still hold a
handle to the renamed file. At most once per reopen_check_interval
seconds each sink compares the inode at path with its open handle
and reopens if they differ (the same approach as the stdlib
WatchedFileHandler). Before rotating, a sink also confirms its
handle is still the file at path, so a stale handle can never make
it rename the new file another worker just created. On Windows a file
another process holds open cannot be renamed, so multi-process
rotation is only supported on POSIX.
Note on retention checks
Applying the retention policy requires listing the log directory and
stat-ing every rotated file in it, which is too expensive to do on
every single log message at real logging volume. Retention is
instead swept immediately after a rotation actually occurs (a new
rotated file just appeared, so it's a natural time to prune old
ones) and otherwise at most once per retention_check_interval
seconds, as a safety net for files that age out between rotations.
Example
safe_file_sink = SafeFileSink( path='logs/app.log', rotation='100 MB', retention='30 days', compression='zip' )
This will set up a log file at 'logs/app.log' with rotation at 100 MB,¶
retention for 30 days, and compression using zip.¶
Source code in dsg_lib/common_functions/logging_config.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | |
apply_retention()
¶
Applies the retention policy to remove old log files.
This method iterates through the rotated log files in the directory of the current log file (never the active log file itself). It checks the modification time of each and removes those older than the specified retention period.
Returns:
| Type | Description |
|---|---|
|
None |
Raises:
| Type | Description |
|---|---|
OSError
|
If there is an error removing a log file. |
Source code in dsg_lib/common_functions/logging_config.py
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | |
parse_duration(duration_str)
staticmethod
¶
Parses a duration string and returns a timedelta object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
duration_str
|
str
|
The duration string (e.g., '7 days'). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
timedelta |
The duration as a timedelta object. |
Source code in dsg_lib/common_functions/logging_config.py
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | |
parse_size(size_str)
staticmethod
¶
Parses a size string and returns the size in bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size_str
|
str
|
The size string (e.g., '100MB'). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
The size in bytes. |
Source code in dsg_lib/common_functions/logging_config.py
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | |
rotate_logs()
¶
Rotates the log file if it exceeds the specified rotation size.
This method checks the size of the current log file. If the file size exceeds the
specified rotation size, it renames the current log file by appending a timestamp to
its name. Optionally, it compresses the rotated log file using the specified
compression method and removes the original uncompressed file. The next write opens
a fresh file at path.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the log file was rotated, False otherwise. |
Raises:
| Type | Description |
|---|---|
OSError
|
If there is an error renaming or compressing the log file. |
Source code in dsg_lib/common_functions/logging_config.py
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |
stop()
¶
Wait for any background compression to finish and close the file.
loguru calls this from logger.remove().
Source code in dsg_lib/common_functions/logging_config.py
289 290 291 292 293 294 295 296 297 298 | |
write(message)
¶
Handles the logging of a message, including writing, rotating, and applying retention policies.
loguru treats any object with a write method as a stream sink and
calls this once per formatted message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The log message to be written. |
required |
This method ensures process-safe logging by acquiring a lock before writing the message
and rotating the logs if necessary. The retention policy is swept immediately after a
rotation, and otherwise at most once per retention_check_interval seconds -- see the
class docstring for why it isn't run on every message.
Source code in dsg_lib/common_functions/logging_config.py
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | |
write_message(message)
¶
Writes a log message to the log file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The log message to be written. |
required |
The message is written to a persistent handle and flushed at once, so other processes and the size check see it immediately.
Source code in dsg_lib/common_functions/logging_config.py
355 356 357 358 359 360 361 362 363 364 365 366 367 | |
config_log(logging_directory='log', log_name='log', logging_level='INFO', log_rotation='100 MB', log_retention='30 days', log_backtrace=False, log_format=None, log_serializer=False, log_diagnose=False, app_name=None, append_app_name=False, enqueue=False, intercept_standard_logging=True, log_propagate=False, compression='zip', log_retention_check_interval=60, intercept_level=None, log_to_file=True, log_to_stdout=False, log_compress_in_background=True)
¶
Configures the logging settings for the application.
This function sets up the logging configuration, including the log directory, log file name, logging level, log rotation, retention policies, and other optional settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logging_directory
|
str
|
The directory where log files will be stored. Defaults to "log". |
'log'
|
log_name
|
str
|
The base name of the log file. Defaults to "log". |
'log'
|
logging_level
|
str
|
The logging level (e.g., "INFO", "DEBUG"). Defaults to "INFO". |
'INFO'
|
log_rotation
|
str
|
The size threshold for log rotation (e.g., "100 MB"). Defaults to "100 MB". |
'100 MB'
|
log_retention
|
str
|
The duration to retain old log files (e.g., "30 days"). Defaults to "30 days". |
'30 days'
|
log_backtrace
|
bool
|
Whether to include backtrace information in logs. Defaults to False. |
False
|
log_format
|
str
|
The format string for log messages. Defaults to a predefined format if not provided. |
None
|
log_serializer
|
bool
|
Whether to serialize log messages. Defaults to False. |
False
|
log_diagnose
|
bool
|
Whether to include diagnostic information in logs. Defaults to False. |
False
|
app_name
|
str
|
The name of the application. Defaults to None. |
None
|
append_app_name
|
bool
|
Whether to append the application name to the log file name. Defaults to False. |
False
|
enqueue
|
bool
|
Whether to route messages through loguru's multiprocessing queue. Defaults to False. The queue pickles every message and sends it through a pipe, which costs several times more per call than the file write itself (about 85 µs vs 11 µs per message in this repo's |
False
|
intercept_standard_logging
|
bool
|
Whether to intercept standard logging calls. Defaults to True. |
True
|
log_propagate
|
bool
|
Whether to propagate log messages to ancestor loggers. Defaults to False. |
False
|
compression
|
str
|
The compression method for rotated log files (e.g., "zip"). Defaults to 'zip'. |
'zip'
|
log_retention_check_interval
|
float
|
Minimum seconds between retention sweeps outside of a rotation event. Retention is always swept immediately after a rotation; this just bounds how often the (directory-scanning) sweep otherwise runs. Defaults to 60. |
60
|
intercept_level
|
str
|
Lowest stdlib |
None
|
log_to_file
|
bool
|
Whether to write to the rotating log file. Defaults to True. |
True
|
log_to_stdout
|
bool
|
Whether to also write to stdout. Defaults to False. For containers that ship stdout, use |
False
|
log_compress_in_background
|
bool
|
Whether rotated files are compressed on a background thread. Defaults to True, so a rotation never blocks the thread that logged while a large file is zipped. |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Returns:
| Type | Description |
|---|---|
|
None |
Example
config_log( logging_directory='logs', log_name='app_log', logging_level='DEBUG', log_rotation='50 MB', log_retention='7 days', log_backtrace=True, log_format='{time} - {level} - {message}', log_serializer=True, log_diagnose=True, app_name='MyApp', append_app_name=True, intercept_standard_logging=False, log_propagate=False, compression='gz' )
This will configure the logging settings with the specified parameters, setting up a log file at 'logs/app_log' with rotation at 50 MB, retention for 7 days, and other specified options.
Container example (JSON lines to stdout, no file): config_log(log_to_file=False, log_to_stdout=True, log_serializer=True)
Source code in dsg_lib/common_functions/logging_config.py
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 | |