python logging file is not working when using logging.basicConfig

前端 未结 5 668
一生所求
一生所求 2021-01-31 08:01

I have the following lines of code that initialize logging. I comment one out and leave the other to be used. The problem that I\'m facing is that the one that is meant to log t

5条回答
  •  臣服心动
    2021-01-31 08:30

    "Changed in version 3.8: The force argument was added." I think it's a better choice for new version.

    From the source code of logging I found the flows:

    This function does nothing if the root logger already has handlers
    
    configured. It is a convenience method intended for use by simple scripts
    to do one-shot configuration of the logging package.
    

    So, if some module we import called the basicConfig() method before us, our call will do nothing.

    A solution I found can work is that you can reload logging before your own calling to basicConfig(), such as

    def init_logger(*, fn=None):
    
        # !!! here
        from imp import reload # python 2.x don't need to import reload, use it directly
        reload(logging)
    
        logging_params = {
            'level': logging.INFO,
            'format': '%(asctime)s__[%(levelname)s, %(module)s.%(funcName)s](%(name)s)__[L%(lineno)d] %(message)s',
        }
    
        if fn is not None:
            logging_params['filename'] = fn
    
        logging.basicConfig(**logging_params)
        logging.error('init basic configure of logging success')
    

提交回复
热议问题