Loguru: how can i logging peewee with loguru

Created on 22 May 2019  ·  2Comments  ·  Source: Delgan/loguru

i use peewee for mysql.
then peewee logging by itself

i also use coloredlogs for logging

# 开启日志
logger = logging.getLogger('peewee')
coloredlogs.install(level=logging.DEBUG, logger=logger)

can i use loguru for peewee logging?

question

Most helpful comment

Hi @visonforcoding.

This is totally possible but this requires a little bit more boilerplate than using coloredlogs, because Loguru doesn't rely on standard logging.

First, you need to create a special Handler in charge of intercepting logs from peewee and redistributing them to Loguru's logger:

class InterceptHandler(logging.Handler):
    def emit(self, record):
        # Retrieve context where the logging call occurred, this happens to be in the 6th frame upward
        logger_opt = logger.opt(depth=6, exception=record.exc_info)
        logger_opt.log(record.levelno, record.getMessage())

Then, you need to add it to the peewee logger as follow:

logging.getLogger("peewee").setLevel(10)
logging.getLogger("peewee").addHandler(InterceptHandler())

That way, peewee logs messages will be propagated to handlers added to Loguru. :+1:

All 2 comments

Hi @visonforcoding.

This is totally possible but this requires a little bit more boilerplate than using coloredlogs, because Loguru doesn't rely on standard logging.

First, you need to create a special Handler in charge of intercepting logs from peewee and redistributing them to Loguru's logger:

class InterceptHandler(logging.Handler):
    def emit(self, record):
        # Retrieve context where the logging call occurred, this happens to be in the 6th frame upward
        logger_opt = logger.opt(depth=6, exception=record.exc_info)
        logger_opt.log(record.levelno, record.getMessage())

Then, you need to add it to the peewee logger as follow:

logging.getLogger("peewee").setLevel(10)
logging.getLogger("peewee").addHandler(InterceptHandler())

That way, peewee logs messages will be propagated to handlers added to Loguru. :+1:

tks! i will try it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zhouxiaomao picture zhouxiaomao  ·  6Comments

volfco picture volfco  ·  5Comments

shmilylty picture shmilylty  ·  5Comments

talz picture talz  ·  6Comments

oz123 picture oz123  ·  4Comments