从带有时间戳的日志中提取信息

时间:2019-01-25 22:32:05

标签: python logging timestamp

我正在从我们的一个硬件模块中读取控制台输出,使用regex通过python脚本提取一些信息,并将该信息写入文件。信息确实提取成功,但我想在每行之前也写timestamp(current)。有没有办法做到这一点?我的控制台输出不显示任何时间戳。

# 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

预期结果:

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

HH:MM:SS总计:1

我能够通过替换

使它正常工作
out_file.write(line) 

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

2 个答案:

答案 0 :(得分:1)

您可以通过

抽出时间
import time

time.time()

或者如果您想要日期和时间

import datetime

datetime.datetime.now()

答案 1 :(得分:1)

我正在使用这个

import time

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

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

也许模块日志记录具有类似的功能?