Logger Core API¶
Core logging classes and factory functions with synchronous and asynchronous APIs, context binding, correlation IDs, and multiple pluggable backends.
Factory Functions¶
get_logger¶
get_logger
¶
get_logger(
name: str, config: LoggerConfig | None = None, force_new: bool = False
) -> Logger
Get a :class:Logger instance.
Convenience wrapper around :meth:Logger.get_logger for callers that
prefer module-level functions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the logger instance. |
required |
config
|
LoggerConfig | None
|
Optional per-logger configuration. |
None
|
force_new
|
bool
|
When |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
Logger |
Logger
|
The logger instance. |
Source code in src/jinpy_utils/logger/core.py
set_global_config¶
set_global_config
¶
set_global_config(config: GlobalLoggerConfig) -> None
Set the global logger configuration.
This forwards to :meth:Logger.set_global_config for convenience.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
GlobalLoggerConfig
|
The global configuration to apply. |
required |
Source code in src/jinpy_utils/logger/core.py
configure_from_env¶
configure_from_env
¶
Configure the global logger from environment variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env_prefix
|
str
|
Prefix used to read environment variables for
configuration (defaults to |
'LOGGER_'
|
Source code in src/jinpy_utils/logger/core.py
shutdown_all_loggers¶
shutdown_all_loggers
¶
Core Classes¶
Logger¶
Logger
¶
High-performance structured logger with async and sync APIs.
The :class:Logger encapsulates configuration, backends, and operational
policy for structured logging. It supports context binding, correlation IDs,
asynchronous processing (when supported by the configured backends), and
exposes convenience helpers for both sync and async application flows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logical name of the logger instance, typically the module or component name. |
required |
config
|
LoggerConfig
|
Per-instance configuration model. |
required |
global_config
|
GlobalLoggerConfig
|
Global configuration applied to all loggers via
:class: |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The logger name. |
config |
LoggerConfig
|
The logger-specific configuration. |
global_config |
GlobalLoggerConfig
|
The active global configuration. |
_context |
dict[str, Any]
|
Baseline structured context bound to the logger. |
_correlation_id |
str | None
|
The current correlation identifier. |
_backends |
list[BackendInterface]
|
Active backend instances. |
Examples:
Basic usage¶
>>> from jinpy_utils.logger import Logger, LoggerManager
>>> from jinpy_utils.logger.config import GlobalLoggerConfig
>>> global_config = GlobalLoggerConfig.from_env()
>>> LoggerManager().set_global_config(global_config)
>>> logger = Logger.get_logger("example")
>>> logger.info("Started", {"version": "1.0.0"})
Context binding¶
Source code in src/jinpy_utils/logger/core.py
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 509 510 511 512 513 514 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 557 558 559 560 561 562 563 564 565 566 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 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 | |
Functions¶
__init__
¶
__init__(name: str, config: LoggerConfig, global_config: GlobalLoggerConfig)
Initialize logger instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logger name |
required |
config
|
LoggerConfig
|
Logger-specific configuration |
required |
global_config
|
GlobalLoggerConfig
|
Global logger configuration |
required |
Source code in src/jinpy_utils/logger/core.py
debug
¶
Log a DEBUG-level message synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The log message content. |
required |
context
|
dict[str, Any] | None
|
Optional structured context for this call. |
None
|
Source code in src/jinpy_utils/logger/core.py
info
¶
Log an INFO-level message synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The log message content. |
required |
context
|
dict[str, Any] | None
|
Optional structured context for this call. |
None
|
Source code in src/jinpy_utils/logger/core.py
warning
¶
Log a WARNING-level message synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The log message content. |
required |
context
|
dict[str, Any] | None
|
Optional structured context for this call. |
None
|
Source code in src/jinpy_utils/logger/core.py
error
¶
Log an ERROR-level message synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The log message content. |
required |
context
|
dict[str, Any] | None
|
Optional structured context for this call. |
None
|
Source code in src/jinpy_utils/logger/core.py
critical
¶
Log a CRITICAL-level message synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The log message content. |
required |
context
|
dict[str, Any] | None
|
Optional structured context for this call. |
None
|
Source code in src/jinpy_utils/logger/core.py
log
¶
log(
level: LogLevel, message: str, context: dict[str, Any] | None = None
) -> None
Log a message at the specified level synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
LogLevel
|
The severity level for the message. |
required |
message
|
str
|
The log message content. |
required |
context
|
dict[str, Any] | None
|
Optional structured context merged into the bound context for this call. Large contexts are truncated in a controlled manner. |
None
|
Raises:
| Type | Description |
|---|---|
JPYLoggerError
|
If logging fails at runtime. |
Source code in src/jinpy_utils/logger/core.py
adebug
async
¶
ainfo
async
¶
awarning
async
¶
aerror
async
¶
acritical
async
¶
Log a CRITICAL-level message asynchronously.
get_stats
¶
Return a snapshot of logger statistics.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Statistics including counters like |
dict[str, Any]
|
|
dict[str, Any]
|
derived metrics such as |
dict[str, Any]
|
information. |
Source code in src/jinpy_utils/logger/core.py
get_backend_stats
¶
Return statistics for all configured backends keyed by name.
Source code in src/jinpy_utils/logger/core.py
bind
¶
bind(**kwargs: Any) -> Logger
Return a child logger with additional bound context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Context key-value pairs to bind permanently to the child logger's baseline context. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Logger |
Logger
|
A new logger instance inheriting configuration and the |
Logger
|
current context plus the provided key-value pairs. |
Source code in src/jinpy_utils/logger/core.py
context
¶
Temporarily bind structured context for nested log calls.
All keyword arguments provided are merged into the logger's bound
context for the duration of the with block.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Key-value pairs to add to the bound context. |
{}
|
Examples:
Source code in src/jinpy_utils/logger/core.py
acontext
async
¶
Temporarily bind structured context in asynchronous flows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Key-value pairs to add to the bound context. |
{}
|
Examples:
Source code in src/jinpy_utils/logger/core.py
flush
async
¶
Flush all pending log entries across async and backend buffers.
When async processing is enabled, this waits for the internal queue to
drain and then awaits any backend flush implementations.
Source code in src/jinpy_utils/logger/core.py
close
async
¶
Close the logger and cleanup resources.
Cancels internal background tasks (if any), flushes all buffers, and closes each backend. Safe to call multiple times.
Source code in src/jinpy_utils/logger/core.py
LoggerManager¶
LoggerManager
¶
Manage global logger configuration and instances.
The manager coordinates a process-wide registry of :class:Logger
instances and provides a single place to set and retrieve the global
configuration. It supports optional singleton behavior so repeated calls
to :meth:get_logger for the same name return the same instance when
enabled in the global configuration.
Thread-safety
All registry mutations are guarded by an internal lock. Reading operations are safe for concurrent use.
Source code in src/jinpy_utils/logger/core.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 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 | |
Functions¶
get_logger
¶
get_logger(
name: str, config: LoggerConfig | None = None, force_new: bool = False
) -> Logger
Get or create a :class:Logger instance.
Behavior depends on the global configuration:
- If singleton mode is enabled and force_new is False (default),
a cached instance for name is returned if present.
- Otherwise a new instance is created.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the logger instance. |
required |
config
|
LoggerConfig | None
|
Optional per-logger configuration. If omitted, a default
:class: |
None
|
force_new
|
bool
|
When |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
Logger |
Logger
|
The logger instance. |
Raises:
| Type | Description |
|---|---|
JPYLoggerConfigurationError
|
If the global configuration is not set
via :meth: |
Source code in src/jinpy_utils/logger/core.py
set_global_config
¶
set_global_config(config: GlobalLoggerConfig) -> None
Set the global logger configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
GlobalLoggerConfig
|
The global configuration to apply to the manager and all
current and future :class: |
required |
Source code in src/jinpy_utils/logger/core.py
shutdown_all
¶
Shutdown all logger instances.
If a running event loop is detected, asynchronous close operations
are scheduled for each logger; otherwise, they are executed using
asyncio.run. This ensures cleanup occurs in both synchronous and
asynchronous application contexts.
This method is idempotent and safe to call multiple times.
Source code in src/jinpy_utils/logger/core.py
Data Models¶
LogEntry¶
LogEntry
¶
Structured log entry with optimized serialization.
Source code in src/jinpy_utils/logger/backends.py
Functions¶
__init__
¶
__init__(
level: LogLevel,
message: str,
logger_name: str,
timestamp: datetime | None = None,
correlation_id: str | None = None,
context: dict[str, Any] | None = None,
module: str | None = None,
function: str | None = None,
line_number: int | None = None,
)
Initialize log entry with optimized memory usage.
Source code in src/jinpy_utils/logger/backends.py
to_dict
¶
Convert to dictionary for serialization.
Source code in src/jinpy_utils/logger/backends.py
Examples¶
Basic Usage¶
from jinpy_utils.logger import get_logger
# Get a logger instance
logger = get_logger("my_app")
# Log messages with structured data
logger.info("User logged in", user_id=123, ip="192.168.1.1")
logger.warning("High memory usage", usage_percent=85.2, threshold=80)
logger.error("Database error", error_code="DB001", retry_count=3)
Advanced Configuration¶
from jinpy_utils.logger import get_logger, LoggerConfig, ConsoleBackendConfig, LogLevel
# Custom configuration
config = LoggerConfig(
level=LogLevel.DEBUG,
backends=[
ConsoleBackendConfig(
level=LogLevel.DEBUG,
use_colors=True,
show_source=True
)
]
)
logger = get_logger("advanced_app", config)
Async Usage¶
import asyncio
from jinpy_utils.logger import get_logger
async def async_operation():
logger = get_logger("async_app")
logger.info("Starting async operation")
await asyncio.sleep(1)
logger.info("Async operation completed")
# The logger automatically handles async contexts
asyncio.run(async_operation())
Context Management¶
from jinpy_utils.logger import get_logger
from contextlib import contextmanager
@contextmanager
def log_operation(operation_name: str):
logger = get_logger("operations")
logger.info(f"Starting {operation_name}")
try:
yield
logger.info(f"Completed {operation_name}")
except Exception as e:
logger.error(f"Failed {operation_name}", error=str(e))
raise
# Usage
with log_operation("user_registration"):
# Your operation here
pass
Global Configuration¶
from jinpy_utils.logger import set_global_config, get_logger, create_production_config
# Set global configuration
set_global_config(create_production_config())
# All subsequent loggers will use the global config
logger1 = get_logger("app1")
logger2 = get_logger("app2")
Environment-Based Setup¶
import os
from jinpy_utils.logger import configure_from_env, get_logger
# Set environment variables
os.environ['JINPY_LOG_LEVEL'] = 'DEBUG'
os.environ['JINPY_LOG_FORMAT'] = 'json'
# Configure from environment
config = configure_from_env()
logger = get_logger("env_app", config)
Cleanup¶
from jinpy_utils.logger import shutdown_all_loggers
# At application shutdown
shutdown_all_loggers()
Performance Considerations¶
Lazy Evaluation¶
The logger uses lazy evaluation for message formatting:
# Efficient - formatting only happens if DEBUG is enabled
logger.debug("Processing item %d of %d", current_item, total_items)
# Less efficient - formatting happens regardless
logger.debug(f"Processing item {current_item} of {total_items}")
Structured Logging Performance¶
# Use keyword arguments for structured fields
logger.info("User action", user_id=123, action="login") # Fast
# Avoid complex objects as values
logger.info("User action", user=user_object) # Slower (serialization)
Async Performance¶
# For high-throughput applications, enable async mode
config = LoggerConfig(async_enabled=True, buffer_size=10000)
logger = get_logger("high_perf", config)
Thread Safety¶
All logger operations are thread-safe:
import threading
from jinpy_utils.logger import get_logger
logger = get_logger("threaded_app")
def worker(worker_id: int):
logger.info("Worker started", worker_id=worker_id)
# Safe to use from multiple threads
# Start multiple threads
threads = [threading.Thread(target=worker, args=(i,)) for i in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
Additional Use Cases¶
HTTP microservice with request-scoped context¶
from contextlib import asynccontextmanager
from jinpy_utils.logger import get_logger
logger = get_logger("api")
@asynccontextmanager
async def request_context(request_id: str, user_id: str | None):
async with logger.acontext(request_id=request_id, user_id=user_id):
yield
async def handle_request(req):
async with request_context(req.id, req.user_id):
await logger.ainfo("request_received", {"path": req.path})
# ... application logic ...
await logger.ainfo("request_completed")
Background worker with batching backends¶
import asyncio
from jinpy_utils.logger import get_logger
logger = get_logger("worker")
async def worker_loop():
while True:
await logger.ainfo("heartbeat")
await asyncio.sleep(5)
asyncio.run(worker_loop())