python logging模块使用
logging 模块最简单使用方法
import logging
logger = logging.getLogger(__name__)
# 输出日志
logger.error("something")
logging 最简单实用的配置
import logging
logger = logging.getLogger(__name__)
LOG_FORMAT = "%(asctime)s %(threadName)s:" + logging.BASIC_FORMAT
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
# 输出日志
logger.info("something")
logging 将日志写入文件最简单实用配置
import logging
logger = logging.getLogger(__name__)
LOG_FORMAT = "%(asctime)s %(threadName)s:" + logging.BASIC_FORMAT
logging.basicConfig(filename="example.log", encoding='utf-8', level=logging.INFO, format=LOG_FORMAT)
# 输出日志
logger.info("something")
这里需要注意,logging的basicConfig方法,在指定filename参数后,初始化的handler为FileHandler,所以在控制台不会有日志打印
logging 将日志写入文件同时在控制台打印
import logging
logger = logging.getLogger(__name__)
LOG_FORMAT = "%(asctime)s %(threadName)s:" + logging.BASIC_FORMAT
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler('example.log', 'a', encoding='utf-8')
file_handler.setFormatter(logging.Formatter(LOG_FORMAT))
logger.addHandler(file_handler)
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter(LOG_FORMAT))
logger.addHandler(console_handler)
# 输出日志
logger.info("something")