python logging file is not working when using logging.basicConfig

前端 未结 5 727
一生所求
一生所求 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:12

    In case basicConfig() does not work:

    logger = logging.getLogger('Spam Logger')
    logger.setLevel(logging.DEBUG)
    # create file handler which logs even debug messages
    fh = logging.FileHandler('spam.log')
    fh.setLevel(logging.DEBUG)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    # create formatter and add it to the handlers
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
    # add the handlers to logger
    logger.addHandler(ch)
    logger.addHandler(fh)
    
    # 'application' code
    logger.debug('debug Spam message')
    logging.debug('debug Spam message')
    logger.info('info Ham message')
    logger.warning('warn Eggs message')
    logger.error('error Spam and Ham message')
    logger.critical('critical Ham and Eggs message')
    

    which gives me the following output:

    2019-06-20 11:33:48,967 - Spam Logger - DEBUG - debug Spam message
    2019-06-20 11:33:48,968 - Spam Logger - INFO - info Ham message
    2019-06-20 11:33:48,968 - Spam Logger - WARNING - warn Eggs message
    2019-06-20 11:33:48,968 - Spam Logger - ERROR - error Spam and Ham message
    2019-06-20 11:33:48,968 - Spam Logger - CRITICAL - critical Ham and Eggs message
    

    For the sake of reference, Python Logging Cookbook is readworthy.

提交回复
热议问题