Seed code for yarf
[ta/yarf.git] / src / yarf / restfullogger.py
1 # Copyright 2019 Nokia
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15
16 import logging
17 import logging.handlers
18 restlogger = None
19
20
21 class RestfulLogger(object):
22     def __init__(self):
23         self.logger = logging.getLogger("Restfulserver")
24         self.logger.setLevel(logging.DEBUG)
25         # werkzug logs out endpoint in DEBUG level, and aaa feature endpoint contains password
26         # in clear text, so log level setting is needed to avoid showing password in journalctl
27         logging.getLogger('werkzeug').setLevel(logging.WARNING)
28         self.handlers = []
29         self.sysloghandler = self._get_syslog_handler()
30         self.handlers.append(self.sysloghandler)
31         self._add_handlers()
32
33     def __del__(self):
34         handlers = self.logger.handlers[:]
35         for handler in handlers:
36             handler.close()
37             self.logger.removeHandler(handler)
38
39     @staticmethod
40     def _get_syslog_handler():
41         sh = logging.handlers.SysLogHandler(address='/dev/log')
42         formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
43         sh.setFormatter(formatter)
44         sh.setLevel(logging.NOTSET)
45         return sh
46
47     def _add_handlers(self):
48         for handler in self.handlers:
49             self.logger.addHandler(handler)
50
51     def get_handlers(self):
52         return self.handlers
53
54     def get_logger(self):
55         return self.logger
56
57 def get_logger():
58     global restlogger
59     if not restlogger:
60         restlogger = RestfulLogger()
61     return restlogger.get_logger()
62
63 def get_log_handlers():
64     global restlogger
65     if not restlogger:
66         restlogger = RestfulLogger()
67     return restlogger.get_handlers()