Loguru is an opinionated yet powerful and user-friendly logging library for Python. It aims to simplify the often complex process of setting up and using logging in applications, providing a more intuitive and feature-rich experience compared to Python's standard `logging` module.
Key features of Loguru include:
- Simplistic Setup: No need for complex `basicConfig()` calls, handlers, formatters, or filters. You simply import `logger` and start logging.
- Automatic File Management: Loguru handles log file rotation, retention, and compression out-of-the-box, significantly reducing boilerplate code for file-based logging.
- Colorized Output: Log messages are automatically colorized in the terminal, improving readability and helping to quickly identify different log levels.
- Structured Logging: Easily log data in a structured format (e.g., JSON), which is crucial for modern log analysis tools.
- Thread-Safe and Process-Safe: Designed to be robust in concurrent environments without manual locking.
- Unhandled Exception Catching: Loguru can automatically intercept unhandled exceptions and log their tracebacks, providing valuable debugging information.
- Variable Depth: Automatically displays the exact location (file, line, function) where a log message originated, configurable for different call depths.
- Customizable Sinks: Allows adding custom destinations (sinks) for log messages, such as files, network sockets, or even custom functions, with fine-grained control over format and level.
Loguru centralizes log dispatching through a single `logger` object. You configure where messages go using the `logger.add()` method, which replaces the concept of handlers and formatters from the standard library. This approach leads to cleaner, more maintainable logging code.
Example Code
from loguru import logger
import sys
import time
By default, Loguru logs to stderr with colorful output
logger.info("This is an informational message.")
logger.debug("A debug message - usually more verbose.")
logger.warning("Something might be going wrong here.")
logger.error("An error occurred!")
logger.critical("Critical issue: application might fail!")
You can remove default sink (stderr) if you want full control
logger.remove()
Add a file sink:
- 'file_{time}.log': The log file name, dynamically named by time.
- rotation="500 MB": Rotates the file when it reaches 500 MB.
- retention="10 days": Deletes log files older than 10 days.
- compression="zip": Compresses old log files into zip archives.
- level="INFO": Only logs INFO level and above to this file.
logger.add(
"file_{time}.log",
rotation="500 MB",
retention="10 days",
compression="zip",
level="INFO",
format="{time} {level} {message}"
)
Add another sink for errors to a separate file,
with a custom format including file and line number
logger.add(
"error.log",
level="ERROR",
format="{time} {level} {file.name}:{line} - {message}"
)
Example of logging with extra data (structured logging)
user_id = 123
request_id = "abc-123"
logger.info("User login attempt.", user_id=user_id, request_id=request_id)
Example with an exception
def divide(a, b):
try:
result = a / b
logger.info(f"Division result: {result}")
return result
except ZeroDivisionError as e:
logger.exception() logs the error with traceback automatically
logger.exception("Attempted to divide by zero!")
return None
divide(10, 2)
divide(5, 0)
Simulate some work
time.sleep(1)
logger.info("Logging complete. Check 'file_-.log' and 'error.log'.")








Loguru