Python之logging打印优雅的日志
封装为为logger_util.py,放在同一文件夹下或同一工程中引用。
import logging
def config_logger(log_level=logging.INFO, log_file=''):
format = '%(asctime)s %(levelname)s %(name)s:%(lineno)d - %(message)s'
if log_file:
logging.basicConfig(format=format, level=log_level, filename=log_file)
else:
logging.basicConfig(format=format, level=log_level)
使用示例:
import logging
from logger_util import config_logger
config_logger(logging.INFO)
logger = logging.getLogger(__name__)
logger.info('开始校验')
logger.error('except,msg = %s' % e)
效果示例:
可以带代码行、时间、区分日志信息和错误信息。