python LogoLogging with Loguru

Logging is a crucial aspect of software development, providing a way to record events that occur while a program runs. These records, often called logs, are invaluable for debugging, monitoring application health, understanding system behavior, and auditing. Python's standard library includes a powerful `logging` module, but it can sometimes be complex to configure, especially for beginners.

`Loguru` is a third-party Python library designed to simplify and enhance the logging experience. It aims to make logging intuitive, efficient, and pleasant to use, abstracting away much of the complexity of the built-in `logging` module.

Key features and advantages of `Loguru`:
- Simplicity: Very easy to set up and use. You get a `logger` instance directly from `loguru` and start logging immediately.
- Default Configuration: Comes with sensible defaults, including colorful console output.
- Flexible Sinks: Easily add different destinations (sinks) for your logs, such as files, the console, network sockets, or even custom functions.
- Automatic Exception Handling: Automatically logs exceptions with full tracebacks without extra configuration.
- Rotation and Retention: Built-in support for rotating log files based on size or time, and retaining a certain number of old log files.
- Compression: Can automatically compress old log files (e.g., to `.zip` or `.gz` formats).
- Customizable Formatting: Offers powerful and flexible formatting options for log messages.
- Thread-safe and Multiprocess-safe: Designed to work robustly in concurrent environments.
- Filtering: Easily filter log messages based on level, module, or custom conditions.

To use `Loguru`, you first need to install it: `pip install loguru`.
Once installed, you simply import `logger` from `loguru` and use its methods like `logger.debug()`, `logger.info()`, `logger.warning()`, `logger.error()`, and `logger.critical()` to record messages at different severity levels. You can configure sinks using `logger.add()` to direct logs to files, change formats, and set up rotation policies, making your logging setup both powerful and straightforward.

Example Code

import sys
from loguru import logger
import time

 --- 1. Basic Setup and Logging ---

 Loguru comes with a default console handler (sink) that prints colored output
logger.info("This is an informational message.")
logger.debug("This is a debug message. (Might not show by default, depending on level)")
logger.warning("This is a warning message.")
logger.error("This is an error message.")

try:
    1 / 0
except ZeroDivisionError:
    logger.exception("An error occurred during division.")  Automatically logs traceback


 --- 2. Adding File Sinks with Rotation and Compression ---

 Remove default console handler to control output more precisely,
 or keep it and add more handlers.
 In this example, let's remove it and add a custom one later.
logger.remove()

 Add a file sink:
 - Logs to 'my_app.log'
 - Rotates the file when it reaches 10 MB
 - Keeps a maximum of 5 old log files
 - Compresses old log files into .zip format
 - Sets the logging level for this sink to INFO
logger.add(
    "my_app.log",
    rotation="10 MB",  Rotate file every 10 MB
    retention="5 days",  Delete log files older than 5 days
    compression="zip",  Compress rotated files
    level="INFO",  Only log INFO and above to this file
    encoding="utf-8"
)

 Add another sink for error logs only
logger.add(
    "my_app_errors.log",
    level="ERROR",  Only log ERROR and above to this file
    rotation="1 week",  Rotate weekly
    compression="gz",  Compress with gzip
    backtrace=True,  Include full backtrace for errors
    diagnose=True  Include variables in traceback for debugging
)

 Add back a console sink, but with a custom format and level
logger.add(
    sys.stderr,  Use standard error stream for console output
    format="{time} {level} {message}",  Simple format
    level="DEBUG",  Show DEBUG messages and above in console
    colorize=True  Enable colorful output
)

logger.debug("This message will only appear in the console (and maybe debug file if configured).")
logger.info("This message will go to console and 'my_app.log'.")
logger.warning("This warning will go to console and 'my_app.log'.")
logger.error("This error will go to console, 'my_app.log', and 'my_app_errors.log'.")

try:
    raise ValueError("Something went wrong!")
except ValueError:
     This will go to all configured sinks, including 'my_app_errors.log' with full details
    logger.exception("An unhandled exception occurred.")

 --- 3. Custom Formatting ---
 Loguru allows very flexible formatting. Let's redefine a sink with a more complex format.
 First, remove the previous console sink to avoid duplicates or reconfigure it.
logger.remove(handler_id=sys.stderr)  Remove by target

logger.add(
    sys.stderr,
    format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
    level="INFO",
    colorize=True
)

logger.info("This message uses a custom, highly detailed console format.")

 You can also disable specific log messages
 logger.disable("my_module")  All logging calls from 'my_module' will be ignored

 Re-enable if needed
 logger.enable("my_module")

 --- 4. Using Extra Fields for Structured Logging ---
logger.bind(user="john.doe").info("User operation initiated.")
logger.bind(order_id="12345", status="processing").warning("Order status update failed.")

 Clean up any remaining handlers if this is the end of the script
 This ensures all buffered logs are written to files before the program exits.
logger.shutdown()

print("\nLogs have been generated. Check 'my_app.log' and 'my_app_errors.log' files.")