简体   繁体   中英

python structlog - can i change log level dynamically but only for specific classes?

my scenario is this - im using a simple logger, and have alot of log.info()/log.debug() messages in my code.

i would like to change the log level dynamically, mainly being able to "turn on/off" debug level logs.

my question is this - is it somehow possible to do so, but make the change only affect parts of my code? lets say only when im inside methods of a specific class. or is the only way to do something like that is to use a different log object for that class and change only its level?

You can achive this by using the stdlib logging output for structlog, and then just configure logging to different levels for each logger.

Every logger has a name, that is used to differenciate where the logs came from and how to handle them. usually you define a single logger per python file like this:

import logging

logger = logging.getLogger(__name__)

What this does is give the logger the name of the python module. for example if the file is proj/routers/route1.py then the logger name will be proj.routers.route1 .
This is useful because the std logging library allows you to configure a log level to the proj.routers logger, that will be applied to every proj.routers.* loggers.

see https://docs.python.org/3/howto/logging.html#configuring-logging

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM