| OLD | NEW |
| (Empty) |
| 1 # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. | |
| 2 # Use of this source code is governed by a BSD-style license that can be | |
| 3 # found in the LICENSE file. | |
| 4 | |
| 5 import os, re | |
| 6 from autotest_lib.client.common_lib import error, utils | |
| 7 from autotest_lib.client.cros.constants import CLEANUP_LOGS_PAUSED_FILE | |
| 8 | |
| 9 class LogReader(object): | |
| 10 """ | |
| 11 A class to read system log files. | |
| 12 """ | |
| 13 | |
| 14 def __init__(self, filename='/var/log/messages'): | |
| 15 self._start_line = 1 | |
| 16 self._filename = filename | |
| 17 if not os.path.exists(CLEANUP_LOGS_PAUSED_FILE): | |
| 18 raise error.TestError('LogReader created without ' + | |
| 19 CLEANUP_LOGS_PAUSED_FILE) | |
| 20 | |
| 21 | |
| 22 def set_start_by_regexp(self, index, regexp): | |
| 23 """Set the start of logs based on a regular expression. | |
| 24 | |
| 25 @param index: line matching regexp to start at, earliest log at 0. | |
| 26 Negative numbers indicate matches since end of log. | |
| 27 """ | |
| 28 regexp_compiled = re.compile(regexp) | |
| 29 file_handle = open(self._filename, 'r') | |
| 30 starts = [] | |
| 31 line_number = 1 | |
| 32 for line in file_handle: | |
| 33 if regexp_compiled.match(line): | |
| 34 starts.append(line_number) | |
| 35 line_number += 1 | |
| 36 if index < -len(starts): | |
| 37 self._start_line = 1 | |
| 38 elif index >= len(starts): | |
| 39 self.set_start_by_current() | |
| 40 else: | |
| 41 self._start_line = starts[index] | |
| 42 | |
| 43 | |
| 44 def set_start_by_reboot(self, index): | |
| 45 """ Set the start of logs (must be system log) based on reboot. | |
| 46 | |
| 47 @param index: reboot to start at, earliest log at 0. Negative | |
| 48 numbers indicate reboots since end of log. | |
| 49 """ | |
| 50 return self.set_start_by_regexp(index, | |
| 51 r'.*000\] Linux version \d') | |
| 52 | |
| 53 | |
| 54 def set_start_by_current(self, relative=1): | |
| 55 """ Set start of logs based on current last line. | |
| 56 | |
| 57 @param relative: line relative to current to start at. 1 means | |
| 58 to start the log after this line. | |
| 59 """ | |
| 60 lines = utils.system_output('wc -l %s' % self._filename) | |
| 61 self._start_line = int(lines.split(' ')[0]) + relative | |
| 62 | |
| 63 | |
| 64 def get_logs(self): | |
| 65 """ Get logs since the start line. | |
| 66 | |
| 67 Start line is set by set_start_* functions or | |
| 68 since the start of the file if none were called. | |
| 69 | |
| 70 @return string of contents of file since start line. | |
| 71 """ | |
| 72 return utils.system_output('tail -n +%d %s' % | |
| 73 (self._start_line, self._filename)) | |
| 74 | |
| 75 def can_find(self, string): | |
| 76 """ Try to find string in the logs. | |
| 77 | |
| 78 @return boolean indicating if we found the string. | |
| 79 """ | |
| 80 return string in self.get_logs() | |
| OLD | NEW |