gpt4 book ai didi

python - 在 Python 中合并和排序日志文件

转载 作者:太空狗 更新时间:2023-10-29 18:18:50 25 4
gpt4 key购买 nike

我是 python 的新手,我有一个我无法解决的严重问题。

我有几个结构相同的日志文件:

[timestamp] [level] [source] message

例如:

[Wed Oct 11 14:32:52 2000] [error] [client 127.0.0.1] error message

我需要用纯 Python 编写一个程序,它将这些日志文件合并到一个文件中,然后按时间戳对合并后的文件进行排序。在此操作之后,我希望将此结果(合并文件的内容)打印到 STDOUT(控制台)。

我不明白该怎么做,希望得到帮助。这可能吗?

最佳答案

你可以这样做

import fileinput
import re
from time import strptime

f_names = ['1.log', '2.log'] # names of log files
lines = list(fileinput.input(f_names))
t_fmt = '%a %b %d %H:%M:%S %Y' # format of time stamps
t_pat = re.compile(r'\[(.+?)\]') # pattern to extract timestamp
for l in sorted(lines, key=lambda l: strptime(t_pat.search(l).group(1), t_fmt)):
print l,

关于python - 在 Python 中合并和排序日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6653371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com