Publishing 2019 R1 content
[platform/upstream/dldt.git] / tools / accuracy_checker / accuracy_checker / logging.py
1 """
2 Copyright (c) 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
18 import logging.config
19 import os
20 import sys
21 import warnings
22
23 _DEFAULT_LOGGER_NAME = 'accuracy_checker'
24 _DEFAULT_LOG_FILE = 'accuracy_checker.log'
25
26 PRINT_INFO = logging.INFO + 5
27 logging.addLevelName(PRINT_INFO, "PRINT_INFO")
28
29 _LOG_LEVEL_ENVIRON = "ACCURACY_CHECKER_LOG_LEVEL"
30 _LOGGING_LEVEL = logging.getLevelName(os.environ.get(_LOG_LEVEL_ENVIRON, PRINT_INFO))
31
32
33 class LoggingFormatter(logging.Formatter):
34     def format(self, record: logging.LogRecord):
35         if record.levelno == PRINT_INFO:
36             return record.msg
37         return super().format(record)
38
39
40 class ConsoleHandler(logging.StreamHandler):
41     def __init__(self, default_stream=sys.stdout):
42         super().__init__(default_stream)
43         self.default_stream = default_stream
44         self.err_stream = sys.stderr
45
46     def emit(self, record):
47         if record.levelno >= logging.WARNING:
48             self.stream = self.err_stream
49         else:
50             self.stream = self.default_stream
51         super().emit(record)
52
53
54 _LOGGING_CONFIGURATION = {
55     'loggers': {
56         _DEFAULT_LOGGER_NAME: {
57             'handlers': ['console'],
58             'level': _LOGGING_LEVEL,
59             'propagate': False
60         }
61     },
62     'version': 1,
63     'disable_existing_loggers': False,
64     'formatters': {
65         'default': {
66             '()': LoggingFormatter,
67             'format': '%(asctime)s %(name)s %(levelname)s: %(message)s',
68             'datefmt': '%H:%M:%S'
69         },
70         'detailed': {
71             'format': '%(asctime)s %(name)s %(levelname)s: %(message)s'
72         }
73     },
74     'handlers': {
75         'console': {
76             'level': 'DEBUG',
77             '()': ConsoleHandler,
78             'formatter': 'default',
79         }
80     }
81 }
82
83 logging.config.dictConfig(_LOGGING_CONFIGURATION)
84
85 _default_logger = logging.getLogger(_DEFAULT_LOGGER_NAME)
86
87
88 def _warning_handler(message, category, filename, line_number):
89     s = warnings.formatwarning(message, category, filename, line_number)
90     _default_logger.warning(s)
91
92
93 warnings.showwarning = _warning_handler
94
95
96 def get_logger(logger_name: str):
97     if logger_name.startswith(_DEFAULT_LOGGER_NAME):
98         return _default_logger.getChild(logger_name)
99     return logging.getLogger(logger_name)
100
101
102 def error(msg, *args, **kwargs):
103     _default_logger.error(msg, *args, **kwargs)
104
105
106 def warning(msg, *args, raise_warning=True, **kwargs):
107     if raise_warning:
108         warnings.warn(msg)
109     else:
110         _default_logger.warning(msg, *args, **kwargs)
111
112
113 def info(msg, *args, **kwargs):
114     _default_logger.info(msg, *args, **kwargs)
115
116
117 def debug(msg, *args, **kwargs):
118     _default_logger.debug(msg, *args, **kwargs)
119
120
121 def print_info(msg, *args, **kwargs):
122     _default_logger.log(PRINT_INFO, msg, *args, **kwargs)
123
124
125 def add_file_handler(file_name):
126     file_info_handler_config = {
127         'level': 'PRINT_INFO',
128         'class': 'logging.handlers.WatchedFileHandler',
129         'formatter': 'default',
130         'filename': file_name
131     }
132     _LOGGING_CONFIGURATION['handlers']['file_info'] = file_info_handler_config
133     _LOGGING_CONFIGURATION['loggers'][_DEFAULT_LOGGER_NAME]['handlers'].append('file_info')
134     logging.config.dictConfig(_LOGGING_CONFIGURATION)