#!/usr/bin/python # -*- coding: UTF-8 -*- ''' ''' import logging # 设置输出文件、文件格式和日志级别 logging.basicConfig(filename='example.log', level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') # 开始打印日志信息 logging.debug('This message should go to the log file') logging.info('So should this') logging.warning('And this, too') logging.warning("user [kobe] attempted wrong password more than 3 times") logging.critical("Server is down...") # 1、创建logger 谁去发日志 logger = logging.getLogger('TEST-LOG') # 先获取logger对象 logger.setLevel(logging.DEBUG) # 设置全局日志级别 # 2、创建Handler 发给屏幕 ch = logging.StreamHandler() # 在屏幕上打印 ch.setLevel(logging.DEBUG) # 设置在屏幕上打印日志的全局级别 # 3、创建Handler 文件 fh = logging.FileHandler("access.log") fh.setLevel(logging.WARNING) # 日志局部级别 fh_err = logging.FileHandler("error.log") fh_err.setLevel(logging.ERROR) # 4、创建formatter输出格式 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') formatter_for_file = logging.Formatter('%(asctime)s - %(filename)s - %(levelname)s - %(message)s') # 5、分别设置格式 ch.setFormatter(formatter) fh.setFormatter(formatter_for_file) fh_err.setFormatter(formatter) # 6、向logger注册 logger.addHandler(ch) logger.addHandler(fh) logger.addHandler(fh_err) # 7、打印 logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message') ''' 运行结果: 写入文件 (example.log) 04/18/2019 10:44:22 AM So should this 04/18/2019 10:44:22 AM And this, too 04/18/2019 10:44:22 AM user [kobe] attempted wrong password more than 3 times 04/18/2019 10:44:22 AM Server is down... 写入文件(access.log) 2019-04-18 10:51:21,851 - man.py - WARNING - warn message 2019-04-18 10:51:21,851 - man.py - ERROR - error message 2019-04-18 10:51:21,851 - man.py - CRITICAL - critical message 写入文件(error.log) 2019-04-18 10:51:21,851 - TEST-LOG - ERROR - error message 2019-04-18 10:51:21,851 - TEST-LOG - CRITICAL - critical message '''