代码
#Author Kang
import logging
logging.basicConfig(filename="app.log",level=logging.WARNING,format=‘%(asctime)s %(levelname)s: %(message)s‘, datefmt=‘%m/%d/%Y %I:%M:%S %p‘)
logging.info("app info test")
logging.warning("app warning message")
logging.error("app error message")
#filename:app.log文件,用于保存日志输出信息
#level:日志级别
#format:日志输出的格式
结果:app.log文件信息
02/18/2019 06:27:10 PM WARNING: app warning message
02/18/2019 06:27:10 PM ERROR: app error message
日志格式
应用代码
#Author Kang
import logging
def loginlog(log_str):
‘‘‘定义了两个日志文件,正常登陆信息写入到access.log,异常登陆信息写入到error.log中‘‘‘
#create logger
logger_access_log = logging.getLogger("Access-log") #创建一个logger(logger_access_log)
logger_access_log.setLevel(logging.INFO) #设置该logger级别,info以上都能接受
logger_error_log = logging.getLogger("Error-log") #创创建一个logger(logger_error_log)
logger_error_log.setLevel(logging.WARNING) #设置该logger级别,warning以上才接受
#create file access.log handler and set level to waring
fh = logging.FileHandler("access.log",encoding="utf-8") #创建一个文件handler(fh)
#create file error.log handler and set level to error
ch = logging.FileHandler("error.log",encoding="utf-8") #创建一个文件handler (ch)
#create formatter
fh_formatter = logging.Formatter(‘%(asctime)s %(levelname)s: %(message)s‘) #fh handler 格式化输出
ch_formatter = logging.Formatter(‘%(asctime)s %(levelname)s: %(message)s‘) #ch handler 格式化出输
#add formatter to fh handler
fh.setFormatter(fh_formatter) #往fh handler 关联格式化
ch.setFormatter(ch_formatter) #往ch handler 关联格式化
#add fh handler to logger
logger_access_log.addHandler(fh) #往logger上添加fh handler
logger_error_log.addHandler(ch) #往logger 上添加ch handler
if "welcome" in log_str:
logger_access_log.info(log_str) #写入日志
else:
logger_error_log.error(log_str) #写入日志
def login():
count = 0
Flag = True
while count < 3:
username = input("请输入你的帐号:")
userpasswd = input("请输入你的密码:")
if username == "root" and userpasswd == "Password1":
print("welcom to %s" %(username))
loginlog("welcome to %s login successful" %(username))
break
else:
print("输入有误,请重新输入")
count+=1
if count == 2:
loginlog("%s login fail" %(username))
login()
原文地址:http://blog.51cto.com/12965094/2351480
时间: 2024-11-06 13:49:12