自“ <date>”以来,Python记录器转储到新文件

问题描述

是否有一种优雅的方法来解析python记录器并创建从时间戳到时间戳的新日志文件?

我们的测试日志文件变得非常长,我想通过给它一个时间戳来破坏日志,因此对于我们要分析的某个时间戳,我们将拥有一个常规日志和一个较小的日志。

打开日志文件并逐行解析将非常耗时,因为我在寻找journalctl --since "2015-01-10 17:15:00" > file.txt命令更苗条的东西

解决方法

这是我的代码,可以做到这一点:

def ParseLogger(filepath=r'C:\tmp\LogParser\Test_log_09-09-2020_17-28-49.txt',start='2020-09-09 17:28:54,013',stop='2020-09-09 17:28:56,444',out_name='test'):
'''
:param filepath: source log file
:param start: start time in format '%Y-%m-%d %H:%M:%S,%f'
:param stop: stop time in format '%Y-%m-%d %H:%M:%S,%f'
:param out_name: log name to be added: Log_{out_name}_start-{start}_stop-{stop}.txt
:return: None
'''
try:
    logPath = os.path.dirname(filepath)
    fileName = f'Log_{out_name}_start-{start.replace(":","")}_stop-{stop.replace(":","")}.txt'
    if not os.path.exists(logPath):
        os.makedirs(logPath)
    LogFile = os.path.join(logPath,fileName)
    f = open(LogFile,"w+")
    with open(filepath) as fp:
        for line in fp:
            try:
                Logtime = re.findall(r"^\[([0-9 -:,]+)\] ",line,re.MULTILINE)[0]
                date_time_obj = datetime.strptime(Logtime,'%Y-%m-%d %H:%M:%S,%f')
                if date_time_obj >= datetime.strptime(start,%f') and date_time_obj <= datetime.strptime(stop,%f'):
                    f.write(line)
                elif date_time_obj > datetime.strptime(stop,%f'):
                    return
            except Exception as e:
                print("skiped line  {} ".format(line))
except Exception as e:
        print('Exception: ' + str(e))
        exc_type,exc_obj,exc_tb = sys.exc_info()
        if exc_type != '' and exc_obj != '' and exc_tb != '':
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type,str(e),fname,exc_tb.tb_lineno)
finally:
    f.close()

日志行示例:[2020-09-10 11:21:46,109]-[系统模块名称]-[信息]-[某些数据]样本txt样本txt样本txt样本txt

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...