1、基本方法日志打印默认只显示级别大于等于WARNINGFATAL:致命错误CRITICAL:特别糟糕的事情,比如内存耗尽,磁盘空间为空,一般很少使用ERROR:发生错误时,比如IO操作失败或者连接问题WARNING:当一个非常重要的事件发生,但不是错误,比如用户登录密码错误INFO:处理请求或者状态变化等日常事务DEBUG:调试时使用DEBUG级别,比如算法中的每个循环中间状态importlogginglogging.debug('Itisadebug')logging.info('Itisainfo')logging.warning('Itisawarning')logging.error('Itisadebug')isaError')logging.critical('Itisacritical')2.设置日志级别importlogginglogging.basicConfig(level=logging.DEBUG)logging.debug('Pythondebug')3.记录信息到文件importlogginglogging.basicConfig(filename='logging.text',level=logging.DEBUG)logging.debug('这是一个debug')logging.info('Itisainfo')logging.warning('Itisawarning')4.更改消息格式%(levelno)s:打印日志级别%(levelname)s的值:打印日志级别的名称%(pathname)s:打印当前执行程序的路径,其实就是sys.argv[0]%(filename)s:打印当前执行程序名称%(funcName)s:打印日志的当前函数%(lineno)d:打印日志的当前行号%(asctime)s:打印日志的时间%(thread)d:打印线程ID%(threadName)s:打印线程name%(process)d:打印进程ID%(message)s:打印日志信息importlogginglogging.basicConfig(format='%(asctime)s%(message)s',datefmt='%m/%d/%Y%I:%M:%S%p')logging.warning('是这个事件被记录的时间。')五、配置日志创建日志配置文件和使用fileConfig()函数读取它的logging.conf配置文件:consoleHandlerqualname=simpleExamplepropagate=0[handler_consoleHandler]class=StreamHandlerlevel=DEBUGformatter=simpleFormatterargs=(sys.stdout,)[formatter_simpleFormatter]format=%(asctime)s-%(name)s-%(levelname)s-%(message)sdatefmt=importloggingimportlogging.configlogging.config.fileConfig('logging.conf')logger=logging.getLogger('simpleExample')logging.debug('Itisadebug')logging.info('Itisainfo')logging.warning('Itisawarning')logging.error('ItisaError')logging.critical('Itisacritical')以上就是本次分享的全部内容,想要学习的朋友们n编程现在欢迎关注Python技术大本营,获取更多技能和教程。
