日志的级别:
DEBUG < INFO < WARNING < ERROR < CRITICAL
日志书写格式:
import logging logging.debug('4444444') logging.info('info message') logging.warning('warning message')
修改logging默认设置(日志保存到文件):
调用basicConfig进行设置
import logging from os.path import dirname, abspath PROJECT_DIR = dirname(dirname(abspath(__file__))) LOG_FORMAT = '%(asctime)s %(name)s %(levelname)s %(pathname)s [line:%(lineno)d] [func:%(funcName)s] %(message)s' # 配置日志输出格式 DATE_FORMAT = '%Y-%m-%d %H:%M:%S %a' # 配置日志中时间输出格式 TODAY = time.strftime('%Y-%m-%d') LOG_DIR = PROJECT_DIR + 'log\' # 配置日志目录 LOG_FILE_NAME = LOG_DIR + TODAY + 'log.log' # 配置日志文件名 logging.basicConfig(level=logging.INFO, # 调用basicConfig进行设置 format=LOG_FORMAT, datefmt=DATE_FORMAT, filename=LOG_FILE_NAME) # 日志输出到文件
basicConfig格式说明:
日志输出到控制台:
定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') console = logging.StreamHandler() console.setLevel(logging.DEBUG) console.setFormatter(formatter) logging.getLogger('').addHandler(console)