面试题答案
一键面试设计思路
- 逐行读取日志文件,解析每行数据,分离出时间戳、操作类型和操作结果。
- 使用一个列表来记录连续失败的登录操作日志。
- 遍历日志文件,当遇到登录失败操作时,将其添加到连续失败列表中;若遇到登录成功操作或其他操作类型,重置连续失败列表。
- 若连续失败列表长度超过3,将该列表中的日志信息写入新文件,并打印首次失败的时间戳。
代码实现
def process_log():
consecutive_failures = []
with open('original_log.log', 'r') as f:
for line in f:
timestamp, operation_type, operation_result = line.strip().split(',')
if operation_type == 'login':
if operation_result == 'failure':
consecutive_failures.append(line)
else:
consecutive_failures = []
else:
consecutive_failures = []
if len(consecutive_failures) > 3:
with open('extracted_log.log', 'w') as new_f:
new_f.writelines(consecutive_failures)
print(consecutive_failures[0].split(',')[0])
break
if __name__ == "__main__":
process_log()
请确保当前目录下存在名为 original_log.log
的日志文件,代码运行后会生成 extracted_log.log
文件并在控制台打印首次失败的时间戳。