Mayil-AI / loguru

MIT License
0 stars 0 forks source link

Question duplicate the warning (hashtag1061) #12

Open vikramsubramanian opened 3 months ago

vikramsubramanian commented 3 months ago

Hi, I have some code that does warnings.warn. I wonder if there is some setting in loguru that would detect warnings.warn raised in other part of the code and record it in the log file? Thanks. Or I have to do both? Like

from loguru import logger
import warning
warning.warn('XXX')
logger.warn('XXX')

)

mayil-ai[bot] commented 3 months ago

To capture warnings issued by the warnings.warn function and log them using Loguru, you can use the warnings module's showwarning method to override the default behavior and send the warnings to the Loguru logger. Here's how you can do it:

import warnings
from loguru import logger

# Function to override the default showwarning
def loguru_showwarning(message, category, filename, lineno, file=None, line=None):
    logger.warning(f"{category.__name__}: {message} (file: {filename}, line: {lineno})")

# Set the Loguru function as the showwarning handler
warnings.showwarning = loguru_showwarning

# Now, when you use warnings.warn, it will be logged by Loguru
warnings.warn('This is a warning message.')

With this setup, you don't need to log the warning message separately using logger.warning. The warnings.warn call will automatically be captured and logged by Loguru.