簡體   English   中英

如何從nodejs或Python中的文件解析日志數據?

[英]How to parse log data from file in nodejs or Python?

我有幾台服務器以這種格式向我提供了包含數百行的文件:

Jun  8 19:17:52 icmp-73260f user.info SM: SM- Security log event: Playout::CPLEnd

Jun  8 19:17:52 icmp-73260f user.info SM: SM- Security log event: Playout::PlayoutComplete

Jun  8 19:17:52 icmp-73260f user.debug SM: IMB Event- End of track CRC values: ffbbffbb - 00c7ffbb - 54c783e4 - 00e483e4

Jun  8 19:17:52 icmp-73260f user.debug SM: IMB Controller- Notify STOPPED state for frame 28465

我如何在python或Nodejs中解析呢?

計划是將它們分為日期,設備,用戶信息,然后是消息。

我計划將此數據存儲在數據庫中,但是我已經介紹了這一部分。

這是在Python中執行此操作的一種簡單方法。 但是,它對日志結構的更改不是很可靠。 如果您認為日志結構會發生很大變化,建議您研究正則表達式。

from datetime import datetime

logs = []

with open("log.txt", "r") as log_file:
  for line in log_file:
    line_list = line.split()
    log = {}
    date = datetime.strptime(" ".join(line_list[:3]), '%b %d %H:%M:%S')
    log['Date'] = date.replace(year=2019) # no year in log
    log['Device'] = line_list[3]
    log['User_info'] = line_list[4]
    log['Message'] = " ".join(line_list[6:])
    logs.append(log)

print(logs)

[   {   'Date': datetime.datetime(2019, 6, 8, 19, 17, 52),
        'Device': 'icmp-73260f',
        'User_info': 'user.info',
        'message': 'SM- Security log event: Playout::CPLEnd'},
    {   'Date': datetime.datetime(2019, 6, 8, 19, 17, 52),
        'Device': 'icmp-73260f',
        'User_info': 'user.info',
        'message': 'SM- Security log event: Playout::PlayoutComplete'},
    {   'Date': datetime.datetime(2019, 6, 8, 19, 17, 52),
        'Device': 'icmp-73260f',
        'User_info': 'user.debug',
        'message': 'IMB Event- End of track CRC values: ffbbffbb - 00c7ffbb - '
                   '54c783e4 - 00e483e4'},
    {   'Date': datetime.datetime(2019, 6, 8, 19, 17, 52),
        'Device': 'icmp-73260f',
        'User_info': 'user.debug',
        'message': 'IMB Controller- Notify STOPPED state for frame 28465'}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM