Language: Python
CLI/Utils
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.
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.
pip install loguruconda install -c conda-forge loguruLoguru 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.
from loguru import logger
logger.info('This is an info message')
logger.warning('This is a warning')Logs messages at different severity levels (info, warning) with minimal setup.
from loguru import logger
logger.add('file.log')
logger.info('This message is saved to a file')Redirects log output to a file, creating it automatically if it doesn’t exist.
from loguru import logger
logger.add('file.log', format='{time} | {level} | {message}', level='INFO')
logger.info('Custom formatted log')Uses a custom log format including time, severity level, and message.
from loguru import logger
logger.add('file_{time}.log', rotation='1 MB')
logger.info('This log will rotate after reaching 1 MB')Automatically rotates log files when they reach a specified size.
from loguru import logger
@logger.catch
def faulty():
x = 1 / 0
faulty()Automatically catches exceptions in functions, logs stack traces, and prevents application crash.
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')Logs messages to multiple outputs (file and console) with independent formatting.
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.