loguru
loguru copied to clipboard
How to output debug only in the console and other level info to the file?
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?
You can re-add a sink logging to stderr.
logger.add(sink=sys.stderr, level="DEBUG")
That's useful! Thanks a lot!!!
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?
You can use a custom filter function:
logger.add(sys.stderr, filter=lambda record: record["level"].name == "DEBUG")
That's nice, help a lot! Thanks again! Maybe add this example to Take the tour can help more people.
@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.