How to change filehandle with Python logging on the fly with different classes and imports

后端 未结 4 595
误落风尘
误落风尘 2020-11-30 23:46

I cannot perform an on-the-fly logging fileHandle change.

For example, I have 3 classes

one.py

import logging
class One():
    d         


        
4条回答
  •  不知归路
    2020-12-01 00:13

    I tried to implemented the suggestions on this page from @Martijn Pieters combined with @Arun Thundyill Saseendran. I'm too new to be allowed to comment so I have to post an adjusted answer. In the isinstance call, I had to use 'logging' instead of 'log' to get access to the types (log was an instance) and then the 'FileHander' should be 'FileHandler'. I'm using Python 3.6.

    import logging
    
    filehandler = logging.FileHandler('/tmp/logfile', 'a')
    formatter = logging.Formatter('%(asctime)-15s::%(levelname)s::%(filename)s::%(funcName)s::%(lineno)d::%(message)s')
    filehandler.setFormatter(formatter)
    log = logging.getLogger()  # root logger - Good to get it only once.
    for hdlr in log.handlers[:]:  # remove the existing file handlers
        if isinstance(hdlr,logging.FileHandler): #fixed two typos here
            log.removeHandler(hdlr)
    log.addHandler(filehandler)      # set the new handler
    # set the log level to INFO, DEBUG as the default is ERROR
    logging.setLevel(log.DEBUG)      
    

提交回复
热议问题