python日志文件处理代码


  1. view plaincopy to clipboardprint?
  2. #! /usr/bin/env python   
  3. # -*- coding: utf-8 -*-   
  4. #@author jinqinghua@gmail.com  
  5. #@version 2010-08-17 02:21  
  6. import os  
  7. import string  
  8. import fileinput  
  9. #日志的位置  
  10. dir_log  = r"D:pythonlogs"
  11. #日志合并后的文件位置  
  12. file_csv = os.path.join(r"F:", "log.csv" )  
  13. if os.path.exists(file_csv):  
  14.     os.remove(file_csv)       
  15. output = open(file_csv, w )  
  16. output.write("ip,line number,error type, error cause ")  
  17. for file in os.listdir(dir_log):  
  18.     if not file.endswith(".log"):  
  19.         print "WARN:%s is not a log file" %(file)  
  20.         continue
  21.     print "INFO:process file %s" %(file)  
  22.     for line in fileinput.input(os.path.join(dir_log, file)):  
  23.         for type in (Caused , ): #ERROR , WARN ):  
  24.             if line.find(type) != -1 :  
  25.                 output.write("%s,%s,%s,%s" %(file[4:16], fileinput.filelineno(), type, string.replace(line, ",", "|")))    
  26.     fileinput.close()  
  27. output.close  
  28. print "done, python is great!"


        应用前提:N台Web机,每天产生大量的日志,先用python脚本从服务器取出,并按xxx_ip_yyyyMMdd_hhmmss.log格式收 集,tar.gz后传到本机,用python将主要的Cause by Error等重要错误信息提取到csv文件,供专人跟踪日志。

相关内容

    暂无相关文章

评论关闭