import logging
def get_logger():
# 创建日志对象
log_obj = logging.getLogger('日志')
# 设置日志水平
log_obj.setLevel(logging.DEBUG)
# 创建控制台句柄
sh = logging.StreamHandler()
# 创建文件句柄
fh = logging.FileHandler('test.log')
# 创建格式对象
log_format = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
# 设置句柄格式
sh.setFormatter(log_format)
fh.setFormatter(log_format)
# 添加句柄到日志对象
log_obj.addHandler(sh)
log_obj.addHandler(fh)
# 返回日志对象
return log_obj
def login(user,pw,log_obj):
if user == '123' and pw == '234':
#登录成功调用日志记录
log_obj.info('用户 %s 登录成功' %user)
else:
#登录失败调用日志记录
log_obj.info('用户 %s 密码错误' %user)
log = get_logger()
login('123','234',log)
来源:CSDN
作者:weixin_38892128
链接:https://blog.csdn.net/weixin_38892128/article/details/103548553