Closed tawada closed 3 months ago
To switch from using Python's built-in logging
module to using loguru
for logging within your project, you'll need to make some modifications. Below, I'll guide you on how to change the utils/logging_utils.py
to utilize loguru
instead of logging
.
First, you'll need to install loguru
if you haven't already. You can do this by running:
pip install loguru
Then, modify your utils/logging_utils.py
to resemble something like the following:
""" Logging utilities for the project updated to use loguru. """
from loguru import logger
from functools import wraps
# Setup loguru logger
def setup_logging():
"""Setup logging for the project."""
logger.remove() # Remove default handler
logger.add(
"debug.log", # Log file path
rotation="100 MB", # New file is created each time the log file reaches 100 MB
retention="10 days", # Logs older than 10 days are deleted
level="INFO"
)
# You can also add stdout logging with custom format
logger.add(
sink=lambda msg: print(msg, flush=True),
format="{time} - {level} - {message}",
level="INFO"
)
# Log message using loguru
def log(message, level="info"):
"""Log a message to the logger with loguru."""
logger_func = getattr(logger, level.lower(), logger.info)
logger_func(message)
# Decorator to handle exceptions and log them
def exception_handler(func):
"""Decorator to handle exceptions in a function."""
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
log(f"An error occurred in {func.__name__}: {str(e)}", level="error")
# Optional: re-raise the exception if you want it to propagate up
raise
return wrapper
This adjusted code:
loguru
for logging, which offers a simpler and more powerful logging system.logger.add()
method from loguru
to configure where logs should be written, their rotation, retention, and their minimum level. log
function to work with loguru
and to retain simplicity. This allows you to log messages with different levels using loguru
's dynamic attribute access.exception_handler
decorator to catch exceptions in decorated functions and log them accordingly.Please adjust the log file path, rotation, and retention values according to your own requirements.
Remember to remove or comment out the original import logging
statement, and any other references to the logging
module in other parts of your project, replacing them with this setup to use loguru
instead.
Please provide specific code on how to change to use loguru.