Извлечение информации из журналов с отметкой времени - PullRequest
0 голосов
/ 26 января 2019

Я читаю вывод консоли из одного из наших аппаратных модулей, извлекаю некоторую информацию с помощью скрипта Python с использованием регулярных выражений и записываю эту информацию в файл.Информация действительно извлекается успешно, но я бы хотел написать метку времени (текущую) перед каждой строкой.Есть способ сделать это?Мой вывод на консоль не отображает отметку времени.

# Regex used to match relevant loglines
line_regex = re.compile(r".*<my_string_1>.*$")
line_regex1 = re.compile(r".*<my_string>.*$")

# Output file, where the matched loglines will be copied to
output_filename = os.path.normpath("parsed_lines.log")
# Overwrites the file, ensure we're starting out with a blank file
with open(output_filename, "w") as out_file:
    out_file.write("")
while 1:
# Open output file in 'append' mode
  with open(output_filename, "a") as out_file:
    # Open input file in 'read' mode
      with open("test_log.txt", "r") as in_file:
        # Loop over each log line
          for line in in_file:
            # If log line matches our regex, print to console, and output file
              if ((line_regex.search(line)) or (line_regex1.search(line))):
                  print (line)
                  sleep (0.5)
                  out_file.write(line)

фактический результат:

ABC054: dur = 354 xfer = 320 wait = 0 proc = 152 total = 152 {file: '../csi/range-1548454834692-0000016887176adb-00112AAA0054-00112AAA0050.json '}

ИТОГО: 1

ожидаемый результат:

ЧЧ: ММ: SS ABC054: длительность= 354 xfer = 320 wait = 0 proc = 152 итого = 152 {file: '../csi/range-1548454834692-0000016887176adb-00112AAA0054-00112AAA0050.json'}

ЧЧ: ММ: СС ИТОГО: 1

Мне удалось заставить его работать, заменив

out_file.write(line) 

на

out_file.write(line.replace("\n", " [%s]\n" % str(datetime.datetime.now()))).

Ответы [ 2 ]

0 голосов
/ 26 января 2019

Я использую это:

import time

def tprint(*args, **kwargs):
    print(time.strftime("%H:%M:%S"), *args, **kwargs)

tprint("hello")
tprint("world")

Может быть, в журнале модулей есть похожая функция?

0 голосов
/ 26 января 2019

Вы можете получить время с помощью

import time

time.time()

Или, если вы хотите дату и время

import datetime

datetime.datetime.now()
...