2017-06-01 190 views
2

我嘗試從我的日誌文件中獲取一個數字。這個數字是在每個「當前商店使用率」之後。我怎樣才能做到這一點?我可以使用re模塊嗎?從日誌文件在文本文件中搜索數字?

2017-05-30 12:01:03,168 | WARN | Store limit is 102400 mb (current store usage is 0 mb). The data directory: /opt/apache-activemq-5.12.0/bin/linux-x86-64/../../data only has 6887 mb of usable space - resetting to maximum available disk space: 6887 mb | org.apache.activemq.broker.BrokerService | WrapperSimpleAppMain 

我的代碼

def log_parser(): 
    palab2 = "WARN" 
    logfile = open("/opt/apache-activemq-5.12.0/data/activemq.log", "r") 
    contenlog = logfile.readlines() 
    logfile.close() 
    for ligne in contenlog: 
     if palab2 in ligne: 
      print ("Probleme : " + ligne) 
+1

不要使用'readlines'讀取整個文件。你可以遍歷每一行。是的,你可以使用're'。 –

回答

0

是的,你可以使用re模塊來大大簡化這一點。並且+1到@Eric Duminil表示建議不要一次讀取整個文件。

import re 

def log_parser(): 
    palab2 = "WARN" 
    logfile = "/opt/apache-activemq-5.12.0/data/activemq.log" 

    with open(logfile, 'r') as contenlog: 
     for ligne in contenlog: 
      if re.findall(palab2, ligne): 
       print ("Probleme : " + ligne) 
       break 
1

這會爲你工作:

import re 
ligne = '2017-05-30 12:01:03,168 | WARN | Store limit is 102400 mb (current store usage is 0 mb). The data directory: /opt/apache-activemq-5.12.0/bin/linux-x86-64/../../data only has 6887 mb of usable space - resetting to maximum available disk space: 6887 mb | org.apache.activemq.broker.BrokerService | WrapperSimpleAppMain' 
print(re.search(r'current store usage is (\d+)', ligne).group(1)) 
# this returns a 'string', you can convert it to 'int' 

輸出:

'0' 

快樂編碼!!!

0

試試這個:

import re 

def log_parser(): 
    with open("/opt/apache-activemq-5.12.0/data/activemq.log", "r") as logfile: 
     for line in logfile: 
      m = re.search(r"current store usage is (\d+)", line): 
       if m: 
        return m.group(1) 

print(log_parser()) 

,如果你只想要第一次出現(我假設的話)或所有這些文件中的行沒有指定。如果後者爲真,只需將return更改爲yield,然後調用如下函數:print(list(log_parser()))