Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / utils / logger.py
1 """
2  Copyright (c) 2018-2019 Intel Corporation
3
4  Licensed under the Apache License, Version 2.0 (the "License");
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15 """
16
17 import logging as log
18 import os
19 import re
20
21 handler_num = 0
22
23
24 class LvlFormatter(log.Formatter):
25     format_dict = {
26         log.DEBUG: "[ %(asctime)s ] [ %(levelname)s ] [ %(module)s:%(lineno)d ]  %(msg)s",
27         log.INFO: "[ %(levelname)s ]  %(msg)s",
28         log.WARNING: "[ WARNING ]  %(msg)s",
29         log.ERROR: "[ %(levelname)s ]  %(msg)s",
30         log.CRITICAL: "[ %(levelname)s ]  %(msg)s",
31         'framework_error': "[ FRAMEWORK ERROR ]  %(msg)s"
32     }
33
34     def __init__(self, lvl, fmt=None):
35         log.Formatter.__init__(self, fmt)
36         self.lvl = lvl
37
38     def format(self, record: log.LogRecord):
39         if self.lvl == 'DEBUG':
40             self._style._fmt = self.format_dict[log.DEBUG]
41         else:
42             self._style._fmt = self.format_dict[record.levelno]
43         if 'is_warning' in record.__dict__.keys():
44             self._style._fmt = self.format_dict[log.WARNING]
45         if 'framework_error' in record.__dict__.keys():
46             self._style._fmt = self.format_dict['framework_error']
47         return log.Formatter.format(self, record)
48
49
50 class TagFilter(log.Filter):
51     def __init__(self, regex: str):
52         self.regex = regex
53
54     def filter(self, record: log.LogRecord):
55         if record.__dict__['funcName'] == 'load_grammar':  # for nx not to log into our logs
56             return False
57         if self.regex:
58             if 'tag' in record.__dict__.keys():
59                 tag = record.__dict__['tag']
60                 return re.findall(self.regex, tag)
61             else:
62                 return False
63         return True  # if regex wasn't set print all logs
64
65
66 def init_logger(lvl: str, silent: bool):
67     global handler_num
68     log_exp = os.environ.get('MO_LOG_PATTERN')
69     if silent:
70         lvl = 'ERROR'
71     fmt = LvlFormatter(lvl=lvl)
72     handler = log.StreamHandler()
73     handler.setFormatter(fmt)
74     logger = log.getLogger()
75     logger.setLevel(lvl)
76     logger.addFilter(TagFilter(regex=log_exp))
77     if handler_num == 0:
78         logger.addHandler(handler)
79         handler_num += 1