Merging and sorting log files in Python

前端 未结 5 1068
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-02 02:58

I am completely new to python and I have a serious problem which I cannot solve.

I have a few log files with identical structure:

[timestamp] [level]         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-02 03:29

    You can do this

    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,
    

提交回复
热议问题