Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

python - 如何为不同的python日志处理程序设置不同的级别(How to set different levels for different python log handlers)

I've read a few posts on this but I'm still confused.

(我已经阅读了一些关于此的文章,但我仍然感到困惑。)

I have this logging setup:

(我有此日志记录设置:)

import logging

class MongoHandler(logging.Handler):
    def __init__(self):
        logging.Handler.__init__(self)
        from pymongo import Connection
        self.db = Connection('db_server').db_name

    def emit(self, record):
        try:
            self.db.Logging.save(record.__dict__)
        except:
            print 'Logging Error:  Unable to save log entry to db'

mh = MongoHandler()
sh = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(threadName)s - %(levelname)s - %(message)s')
sh.setFormatter(formatter)
log = logging.getLogger('DeviceMonitor_%s' % hostname)
log.addHandler(mh)
log.addHandler(sh)
log.setLevel(logging.INFO)

I want to be able to set a different level for the StreamHandler and the MongoHandler.

(我希望能够为StreamHandler和MongoHandler设置不同的级别。)

Is that possible or do I need to have a second Logger obj?

(有可能吗,或者我需要第二个Logger obj?)

  ask by MFB translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can set a different logging level for each logging handler but it seems you will have to set the logger's level to the "lowest".

(您可以为每个日志记录处理程序设置不同的日志记录级别,但是似乎您必须将记录器的级别设置为“最低”。)

In the example below I set the logger to DEBUG, the stream handler to INFO and the TimedRotatingFileHandler to DEBUG.

(在下面的示例中,我将记录器设置为DEBUG,将流处理程序设置为INFO,并将TimedRotatingFileHandler设置为DEBUG。)

So the file has DEBUG entries and the stream outputs only INFO.

(因此,该文件具有DEBUG条目,并且流仅输出INFO。)

You can't direct only DEBUG to one and only INFO to another handler.

(您不能仅将DEBUG定向到一个,而只能将INFO定向到另一个处理程序。)

For that you'll need another logger.

(为此,您将需要另一个记录器。)

logger = logging.getLogger("mylog")
formatter = logging.Formatter(
    '%(asctime)s | %(name)s |  %(levelname)s: %(message)s')
logger.setLevel(logging.DEBUG)

stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(formatter)

logFilePath = "my.log"
file_handler = logging.handlers.TimedRotatingFileHandler(
    filename=logFilePath, when='midnight', backupCount=30)
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)

logger.addHandler(file_handler)
logger.addHandler(stream_handler)

logger.info("Started");
try:
    x = 14
    y = 0
    z = x / y
except Exception as ex:
    logger.error("Operation failed.")
    logger.debug(
        "Encountered {0} when trying to perform calculation.".format(ex))

logger.info("Ended");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...