python logging模块
1. 打印日志到屏幕
import logging logging.info(' infog....') logging.debug('debug.....') logging.warning('warn...') 打印结果: WARNING:root:warn...
默认情况下,logging将日志打印到屏幕,日志级别为WARNING;
日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,当然也可以自己定义日志级别
2. 通过logging.basicConfig()函数对日志的输出格式及方式做相关配置
import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s %(levelname)s %(message)s', datefmt='%Y%-%m-%d %H:%M:%S', filename='2017-12-18.log', filemode='w' ) logging.warning('this is warning .....') logging.debug('this is debug.....') logging.info('this is info ....')
各个参数解释:
level:设置日志级别,默认是logging.warning
format:指定输出的格式和内容,打印以下信息:
%(asctime)s:打印日志的时间 ---datefmt
%(filename)s:打印当前执行程序名 ---- demo.py
%(levelname)s:打印日志级别名称 --- INFO/DEBUG。。。
%(message)s: 打印日志信息
datefmt :指定打印日志的时间格式 xxxx-xx-xx xx:xx:xx, 类似time.strftime( %Y%m%d %H%M%S)
filename:指定日志文件名
filemode :指定打开日志文件的格式 w 或 a
stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略
运行结果:
2017-12-19 15:18:52 demo.py WARNING this is warning ..... 2017-12-19 15:18:52 demo.py DEBUG this is debug..... 2017-12-19 15:18:52 demo.py INFO this is info ....
简单举例:
""" 主要是打印日志时间、日志级别、日志信息 """ import logging import sys import os import time from until.file_system import get_log_dir from until.config_parser import ConfigParser """ 打印日志信息 """ def get_num_level(level): level_dict= { "CRITICAL": 50, "FATAL": 50, "ERROR": 40, "WARNING": 30, "WARN": 30, "INFO": 20, "DEBUG": 10, "NOTSET": 0, } return level_dict[level.upper()] """ 打印日志信息 """ def print_log(log, level='info'): current = time.strftime('%Y-%m-%d', time.localtime(time.time())) formatter = logging.Formatter('%(asctime)s - %(levelname)-5s - %(message)s') logger = logging.getLogger('MEMPium') logger.setLevel(logging.DEBUG) log_path = get_log_dir() # 获取日志所在目录 if "FileHandler" not in str(logger.handlers): fh = logging.FileHandler( log_path + os.sep + "%s.log" % current, encoding="UTF-8" ) fh.setLevel(int(ConfigParser().get_config("logging", "level"))) #获取配置文件 logging配置下 level的级别 fh.setFormatter(formatter) logger.addHandler(fh) if "StreamHandler" not in str(logger.handlers): ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) logger.addHandler(ch) logger.log(get_num_level(level), log) if __name__ == '__main__': res = print_log('hahah', 'error')
后续补充~~~~
参考链接:
https://www.cnblogs.com/dkblog/archive/2011/08/26/2155018.html