@cryptotaxi247 / netdata-1 / commits / 62bc33edf

move LogService to a separate file

lgz committed Oct 13, 2017 at 00:15 UTC 62bc33edfb1d18e14a4ec6b487fdf5cc8892c6b1
1 file changed +77
python.d/python_modules/bases/FrameworkServices/LogService.py new
+77
@@ -0,0 +1,77 @@
1 +# -*- coding: utf-8 -*-
2 +# Description:
3 +# Author: Pawel Krupa (paulfantom)
4 +
5 +from glob import glob
6 +
7 +from bases.FrameworkServices.SimpleService import SimpleService
8 +
9 +
10 +class LogService(SimpleService):
11 + def __init__(self, configuration=None, name=None):
12 + SimpleService.__init__(self, configuration=configuration, name=name)
13 + self.log_path = self.configuration.get('path')
14 + self.__glob_path = self.log_path
15 + self._last_position = 0
16 + self.__re_find = dict(current=0, run=0, maximum=60)
17 +
18 + def _get_raw_data(self):
19 + """
20 + Get log lines since last poll
21 + :return: list
22 + """
23 + lines = list()
24 + try:
25 + if self.__re_find['current'] == self.__re_find['run']:
26 + self._find_recent_log_file()
27 + size = self.functions.get_file_size(self.log_path)
28 + if size == self._last_position:
29 + self.__re_find['current'] += 1
30 + return list() # return empty list if nothing has changed
31 + elif size < self._last_position:
32 + self._last_position = 0 # read from beginning if file has shrunk
33 +
34 + with open(self.log_path) as fp:
35 + fp.seek(self._last_position)
36 + for line in fp:
37 + lines.append(line)
38 + self._last_position = fp.tell()
39 + self.__re_find['current'] = 0
40 + except (OSError, IOError) as error:
41 + self.__re_find['current'] += 1
42 + self.error(str(error))
43 +
44 + return lines or None
45 +
46 + def _find_recent_log_file(self):
47 + """
48 + :return:
49 + """
50 + self.__re_find['run'] = self.__re_find['maximum']
51 + self.__re_find['current'] = 0
52 + self.__glob_path = self.__glob_path or self.log_path # workaround for modules w/o config files
53 + path_list = glob(self.__glob_path)
54 + if path_list:
55 + self.log_path = max(path_list)
56 + return True
57 + return False
58 +
59 + def check(self):
60 + """
61 + Parse basic configuration and check if log file exists
62 + :return: boolean
63 + """
64 + if not self.log_path:
65 + self.error('No path to log specified')
66 + return None
67 +
68 + if self._find_recent_log_file() and self.functions.is_file_readable(self.log_path):
69 + return True
70 + self.error('Cannot access {0}'.format(self.log_path))
71 + return False
72 +
73 + def create(self):
74 + # set cursor at last byte of log file
75 + self._last_position = self.functions.get_file_size(self.log_path)
76 + status = SimpleService.create(self)
77 + return status