1、打印到控制台
# -*- coding: UTF-8 -*- import logging def logFileTest(): logging.debug(‘This is debug‘) logging.warning(‘This is warning message‘) logging.info(‘This is info‘) logFileTest()
运行结果
WARNING:root:This is warning message
PS : 只有 logging.warning() 能打印输出到控制台,因为默认设置的等级是 warning
2、配置默认等级后,打印到控制台
# -*- coding: UTF-8 -*- import logging def logBasicConfig(): logging.basicConfig(level=logging.DEBUG) logging.debug(‘This is debug‘) logging.warning(‘This is warning message‘) logging.info(‘This is info‘) logBasicConfig()
运行结果
DEBUG:root:This is debug WARNING:root:This is warning message INFO:root:This is info
PS : 日志级别: debug < info < warning < error < critical
3、保存到日志文件中,通过 logging.basicConfig() 设置
# -*- coding: UTF-8 -*- import logging def saveToLogFile(): logging.basicConfig( filename = ‘saveMessage.log‘, #保存文件路径 filemode = ‘a‘,#保存方式,有 w 和 a 模式,默认不写为追加 a 模式 format = ‘%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s‘ #日志格式 ) logging.warning(‘This is warning‘) saveToLogFile()
运行结果
2019-08-27 14:00:58,463 - D:\E_DISK\product\eclipse\logFileDemo\src\com\logFileDemo.py[line:24] - WARNING: This is warning
PS : 这是 saveMessage.log 文件中生成的日志信息
如果在 logging.basicConfig() 设置 filename 和 filemode,则只会保存 log 到文件,不会输出到控制台
4、关于日志回滚(分割日志文件)请参考 https://www.cnblogs.com/nancyzhu/p/8551506.html 该文章也是学习该博客的笔记
原文:https://www.cnblogs.com/rainbow-tan/p/11418293.html