loguru icon indicating copy to clipboard operation
loguru copied to clipboard

How to output debug only in the console and other level info to the file?

Open AaronWaxson opened this issue 3 years ago • 6 comments

I try to make my information output to different destination, like level info and higher infomartion output to file, debug information output to the console. Here's my code now:

from loguru import logger
logger.remove()
logger.add(sink='runtime_{time}.log', rotation='500 MB', level='INFO')

logger.debug('something')
logger.info('others')

Now all information is disable to output. What should I do?

AaronWaxson avatar Aug 01 '22 08:08 AaronWaxson

You can re-add a sink logging to stderr.

logger.add(sink=sys.stderr, level="DEBUG")

Delgan avatar Aug 01 '22 11:08 Delgan

That's useful! Thanks a lot!!!

AaronWaxson avatar Aug 01 '22 12:08 AaronWaxson

I am sorry for coming again, but I found my question not fixed entirely.... After I add above code, all my log info output to the console, but I only want the debug info output to the console, the other level info output to the file, and information work flow would like:

from loguru import logger
logger.remove()
logger.add(sink='runtime_{time}.log', rotation='500 MB', level='INFO')

logger.debug('first loop')
for i in range(10):
    logger.info('others')
logger.debug('done')
logger.debug('second loop')
for i in range(10):
    logger.info('others')
logger.debug('done')

Can this thought achieve?

AaronWaxson avatar Aug 01 '22 12:08 AaronWaxson

You can use a custom filter function:

logger.add(sys.stderr, filter=lambda record: record["level"].name == "DEBUG")

Delgan avatar Aug 01 '22 13:08 Delgan

That's nice, help a lot! Thanks again! Maybe add this example to Take the tour can help more people.

AaronWaxson avatar Aug 01 '22 13:08 AaronWaxson

@AaronWaxson Actually, I do consider this to be a good practice of logging, so I prefer not to. :grin:

It's better in my opinion to have a minimum threshold level, instead of a exact one: if you're interested in details from "DEBUG" messages (for example), you likely need the messages from upper levels as well, because otherwise you lose information about the overall flow of your application. For example, you can use "DEBUG" messages to investigate an "ERROR" appearing in logs, but you'll lose context if you explicitly filtered out errors messages.

Delgan avatar Aug 01 '22 16:08 Delgan