Advertisement
Guest User

tomcat log analyzer

a guest
Nov 1st, 2012
394
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.54 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. # Version: 0.1
  4. # Author: rad <[email protected]>
  5. # License: GPL 3
  6. #
  7.  
  8. import sys
  9. import codecs
  10. import re
  11. import argparse
  12.  
  13. class ErrorInfo:
  14.     def __init__(self):
  15.         self.dates = []
  16.     def add_date(self, date):
  17.         self.dates.append(date)
  18.     @property
  19.     def err_count(self):
  20.         return str(len(self.dates))
  21.  
  22. def read_error(file):
  23.     text = "";
  24.     for line in file:
  25.         if time_re.search(line):
  26.             return text;
  27.         text += line
  28.     return text # срабатаывает для ошибки в конце файла, и если не сработал time_re то содержит текст всего лога, надо что-то делать
  29.    
  30. def read_errors(file_name, errors):
  31.     counter = 0;
  32.     file = codecs.open(file_name, mode="r", encoding="utf-8")
  33.     old_line = None
  34.     for line in file:
  35.         if line.startswith("SEVERE"):
  36.             mo = time_re.search(old_line)
  37.             if not mo:
  38.                 continue
  39.             date = mo.group()
  40.             counter += 1
  41.             error = line;
  42.             other = read_error(file)
  43.             if other:
  44.                 error += other
  45.             if error:
  46.                 info = errors.get(error)
  47.                 if not info:
  48.                     info = ErrorInfo()
  49.                     errors[error] = info;
  50.                 info.add_date(date)
  51.         else:
  52.           old_line = line
  53.          
  54. if __name__ == "__main__":
  55.     ap = argparse.ArgumentParser(description="Java log analyzer")
  56.     ap.add_argument('log_files',
  57.                     metavar='log',
  58.                     type=str,
  59.                     nargs='+',
  60.                     help='log files for analyzing')
  61.     ap.add_argument('-t',
  62.                     dest='time_pattern',
  63.                     default="([\d.]+ [\d:]+)|([\w]+ \d+, \d{4} [\d:]+ [A|P]M)",
  64.                     help='time regular expression patten (for example like "([\d.]+ [\d:]+)|([\w]+ \d+, \d{4} [\d:]+ [A|P]M)" )')
  65.     ap.add_argument('-o',
  66.                     dest='out_file',
  67.                     help='analyze report file (XML)')
  68.     args = ap.parse_args(sys.argv[1:])
  69.     time_re = re.compile("^(?:" + args.time_pattern + ")", re.UNICODE)
  70.     file_names = args.log_files
  71.     errors = {}
  72.     for file_name in file_names:
  73.         read_errors(file_name, errors)
  74.     with codecs.open(args.out_file, 'w', 'utf-8') as out:
  75.         out.write('''<?xml-stylesheet href="#style" type="text/css"?>
  76. <errors>
  77.    <style id="style">
  78.        style {
  79.            display:none;
  80.        }
  81.        error, dates, date, title, text {
  82.            display:block;
  83.        }
  84.        error {
  85.            border-top: solid 1px gray;
  86.        }
  87.        count {
  88.            background-color:red;
  89.        }
  90.        date {
  91.            margin-left:40px;
  92.            display: list-item;
  93.            list-style-type:round;
  94.        }
  95.        text {
  96.            font-family: monospace;
  97.            white-space: pre;
  98.        }
  99.    </style>''')
  100.         for error_text, info in errors.items():
  101.             out.write("\t<error>\n" +
  102.                   u"\t\t<title>Ошибка повторилась <count>" + info.err_count + u"</count> раз</title>\n" +
  103.                   "\t\t<dates>\n")
  104.             for date in info.dates:
  105.                 out.write("\t\t\t<date>" + date + "</date>\n")
  106.             out.write("\t\t</dates>\n" +
  107.                   "\t<text><![CDATA[" + error_text + "]]></text>\n"
  108.                   "</error>")
  109.         out.write("</errors>\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement