先上源码:
import logging
def flogcfg(logfile='./proc.log', flevel=logging.INFO):
fhandler = logging.FileHandler(logfile, mode='w', encoding="utf8")
fmt = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s.%(lineno)d %(name)s:\t%(message)s')
fhandler.setFormatter(fmt)
fhandler.setLevel(flevel)
logging.basicConfig(level=flevel,
handlers=[fhandler])
logger = logging.getLogger()
return logger
def flogcfg_test(logfile='./proc.log'):
logger = flogcfg(logfile)
print(22222222222)
logger.info("info")
logger.warning("warning")
logger.error('1111111')
print(333333333)
logger.critical("critical")
if __name__ == '__main__':
flogcfg_test()
运行这个代码在一个地方可以把信息输出到文件,在另外一个却不能输出到文件,而是打印命令终端,百思不得其解,最后跟踪发现问题出在
logger = logging.getLogger()这行代码
不知咋回事,程序运行完这行代码出现如下截图情况:
看到没有logger下的handlers[0]属性居然是
import logging
def flogcfg(logfile='./proc.log', flevel=logging.INFO):
fhandler = logging.FileHandler(logfile, mode='w', encoding="utf8")
fmt = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s.%(lineno)d %(name)s:\t%(message)s')
fhandler.setFormatter(fmt)
fhandler.setLevel(flevel)
logging.basicConfig(level=flevel,
handlers=[fhandler])
logger = logging.getLogger()
logger.handlers[0] = fhandler
return logger
def flogcfg_test(logfile='./proc.log'):
logger = flogcfg(logfile)
print(22222222222)
logger.info("info")
logger.warning("warning")
logger.error('1111111')
print(333333333)
logger.critical("critical")
if __name__ == '__main__':
flogcfg_test()