What it is
Loguru is a Python library that simplifies logging by providing an easy-to-use, flexible, and powerful logging system. It reduces boilerplate code and adds features like sink management, message formatting, and exception catching.
Loguru allows you to log messages with various severity levels, format logs with colors, redirect logs to files, and catch exceptions automatically. It supports both synchronous and asynchronous applications and can be easily integrated into existing projects.
Installation
pip install loguruGetting started
The smallest useful thing you can do with it, and what each part means.
from loguru import logger
logger.info('This is an info message')
logger.warning('This is a warning')from loguru import logger
logger.add('file.log')
logger.info('This message is saved to a file')Advanced usage
Where the library earns its place over a simpler alternative.
from loguru import logger
logger.add('file.log', format='{time} | {level} | {message}', level='INFO')
logger.info('Custom formatted log')from loguru import logger
logger.add('file_{time}.log', rotation='1 MB')
logger.info('This log will rotate after reaching 1 MB')from loguru import logger
@logger.catch
def faulty():
x = 1 / 0
faulty()from loguru import logger
logger.add('file.log')
logger.add(sys.stderr, colorize=True, format='<green>{time}</green> | {level} | {message>')
logger.info('Logged to both file and console')Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- FileNotFoundError
- Ensure the specified log file path exists or use a valid path.
- PermissionError
- Check file permissions and ensure the application can write to the log file.
Best practices
- Use `logger.add()` to manage multiple log destinations and formats.
- Use `@logger.catch` to simplify exception handling and logging.
- Set appropriate log levels for different environments (DEBUG for development, WARNING/ERROR for production).
- Rotate and compress log files to prevent storage issues.
- Avoid excessive logging in performance-critical code sections.
Background
Why it exists, and what it was reacting to.
Loguru was created by Delgan in 2017 to offer a simpler, more intuitive logging experience than Python's built-in `logging` module. It aims to streamline logging setup and usage while providing advanced capabilities such as structured logging, colored outputs, and file rotation.
