-
Notifications
You must be signed in to change notification settings - Fork 2
/
AutoBlindLogger.py
245 lines (213 loc) · 8.18 KB
/
AutoBlindLogger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#!/usr/bin/env python3
# vim: set encoding=utf-8 tabstop=4 softtabstop=4 shiftwidth=4 expandtab
#########################################################################
# Copyright 2014- Thomas Ernst [email protected]
#########################################################################
# Finite state machine plugin for SmartHomeNG
#
# This plugin is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This plugin is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this plugin. If not, see <http://www.gnu.org/licenses/>.
#########################################################################
import logging
import datetime
import os
class AbLogger:
# Log-Level: (0=off 1=Info, 2=Debug)
__loglevel = 2
# Target directory for log files
__logdirectory = "/usr/local/smarthome/var/log/AutoBlind/"
# Max age for log files (days)
__logmaxage = 0
# Set log level
# loglevel: current loglevel
@staticmethod
def set_loglevel(loglevel):
try:
AbLogger.__loglevel = int(loglevel)
except ValueError:
AbLogger.__loglevel = 2
logger = logging.getLogger('plugins.autoblind.AutoBlindLogger')
logger.error("Das Log-Level muss numerisch angegeben werden.")
# Set log directory
# logdirectory: Target directory for AutoBlind log files
@staticmethod
def set_logdirectory(logdirectory):
AbLogger.__logdirectory = logdirectory
# Set max age for log files
# logmaxage: Maximum age for log files (days)
@staticmethod
def set_logmaxage(logmaxage):
try:
AbLogger.__logmaxage = int(logmaxage)
except ValueError:
AbLogger.__logmaxage = 0
logger = logging.getLogger('plugins.autoblind.AutoBlindLogger')
logger.error("Das maximale Alter der Logdateien muss numerisch angegeben werden.")
@staticmethod
def remove_old_logfiles():
if AbLogger.__logmaxage == 0:
return
logger = logging.getLogger('plugins.autoblind.AutoBlindLogger')
logger.info("Removing logfiles older than {0} days".format(AbLogger.__logmaxage))
count_success = 0
count_error = 0
now = datetime.datetime.now()
for file in os.listdir(AbLogger.__logdirectory):
if file.endswith(".log"):
try:
abs_file = os.path.join(AbLogger.__logdirectory, file)
stat = os.stat(abs_file)
mtime = datetime.datetime.fromtimestamp(stat.st_mtime)
age_in_days = (now - mtime).total_seconds() / 86400.0
if age_in_days > AbLogger.__logmaxage:
os.unlink(abs_file)
count_success += 1
except Exception as ex:
logger.error(str(ex))
count_error += 1
logger.info("{0} files removed, {1} errors occured".format(count_success, count_error))
# Return AbLogger instance for given item
# item: item for which the detailed log is
@staticmethod
def create(item):
return AbLogger(item)
# Constructor
# item: item for which the detailed log is (used as part of file name)
def __init__(self, item):
self.logger = logging.getLogger(__name__)
self.__section = item.id().replace(".", "_").replace("/", "")
self.__indentlevel = 0
self.__date = None
self.__filename = ""
self.update_logfile()
# Update name logfile if required
def update_logfile(self):
if self.__date == datetime.datetime.today() and self.__filename is not None:
return
self.__date = str(datetime.date.today())
self.__filename = str(AbLogger.__logdirectory + self.__date + '-' + self.__section + ".log")
# Increase indentation level
# by: number of levels to increase
def increase_indent(self, by=1):
self.__indentlevel += by
# Decrease indentation level
# by: number of levels to decrease
def decrease_indent(self, by=1):
if self.__indentlevel > by:
self.__indentlevel -= by
else:
self.__indentlevel = 0
# log text something
# level: required loglevel
# text: text to log
def log(self, level, text, *args):
# Section givn: Check level
if level <= AbLogger.__loglevel:
indent = "\t" * self.__indentlevel
text = text.format(*args)
logtext = "{0}{1} {2}\r\n".format(datetime.datetime.now(), indent, text)
with open(self.__filename, mode="a", encoding="utf-8") as f:
f.write(logtext)
# log header line (as info)
# text: header text
def header(self, text):
self.__indentlevel = 0
text += " "
self.log(1, text.ljust(80, "="))
# log with level=info
# @param text text to log
# @param *args parameters for text
def info(self, text, *args):
self.log(1, text, *args)
# log with lebel=debug
# text: text to log
# *args: parameters for text
def debug(self, text, *args):
self.log(2, text, *args)
# log warning (always to main smarthome.py log)
# text: text to log
# *args: parameters for text
# noinspection PyMethodMayBeStatic
def warning(self, text, *args):
self.log(1, "WARNING: " + text, *args)
self.logger.warning(text.format(*args))
# log error (always to main smarthome.py log)
# text: text to log
# *args: parameters for text
# noinspection PyMethodMayBeStatic
def error(self, text, *args):
self.log(1, "ERROR: " + text, *args)
self.logger.error(text.format(*args))
# log exception (always to main smarthome.py log'
# msg: message to log
# *args: arguments for message
# **kwargs: known arguments for message
# noinspection PyMethodMayBeStatic
def exception(self, msg, *args, **kwargs):
self.log(1, "EXCEPTION: " + str(msg), *args)
self.logger.exception(msg, *args, **kwargs)
class AbLoggerDummy:
# Constructor
# item: item for which the detailed log is (used as part of file name)
# noinspection PyUnusedLocal
def __init__(self, item=None):
self.logger = logging.getLogger(__name__)
# Update name logfile if required
def update_logfile(self):
pass
# Increase indentation level
# by: number of levels to increase
def increase_indent(self, by=1):
pass
# Decrease indentation level
# by: number of levels to decrease
def decrease_indent(self, by=1):
pass
# log text something
# level: required loglevel
# text: text to log
def log(self, level, text, *args):
pass
# log header line (as info)
# text: header text
def header(self, text):
pass
# log with level=info
# @param text text to log
# @param *args parameters for text
def info(self, text, *args):
pass
# log with lebel=debug
# text: text to log
# *args: parameters for text
def debug(self, text, *args):
pass
# log warning (always to main smarthome.py log)
# text: text to log
# *args: parameters for text
# noinspection PyMethodMayBeStatic
def warning(self, text, *args):
self.logger.warning(text.format(*args))
# log error (always to main smarthome.py log)
# text: text to log
# *args: parameters for text
# noinspection PyMethodMayBeStatic
def error(self, text, *args):
self.logger.error(text.format(*args))
# log exception (always to main smarthome.py log'
# msg: message to log
# *args: arguments for message
# **kwargs: known arguments for message
# noinspection PyMethodMayBeStatic
def exception(self, msg, *args, **kwargs):
self.logger.exception(msg, *args, **kwargs)