1# Copyright 2023 Huawei Technologies Co., Ltd 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""" 16log for mslite bench 17""" 18import logging 19from functools import wraps 20 21 22def singleton(cls): 23 """singleton decorator function""" 24 instances_ = {} 25 26 @wraps(cls) 27 def _get_instances(*args, **kwargs): 28 if cls not in instances_: 29 instances_[cls] = cls(*args, **kwargs) 30 return instances_.get(cls, None) 31 32 return _get_instances 33 34 35@singleton 36class InferLogger: 37 """ 38 logger for mslite bench, with singleton decorated 39 """ 40 def __init__(self, file_path: str = None): 41 self.file_path = file_path 42 self.logger_ = self._create_logger() 43 44 @property 45 def logger(self): 46 return self.logger_ 47 48 def set_level(self, level=logging.info): 49 self.logger_.setLevel(level) 50 51 def _create_logger(self): 52 """create logger for mslite bench""" 53 logger = logging.getLogger('MSLITE_BENCH') 54 log_format = '%(asctime)s - [%(name)s-%(levelname)s' \ 55 '(%(filename)s:%(lineno)d)]: %(message)s' 56 formatter = logging.Formatter(log_format, 57 datefmt='%m/%d %I:%M:%S %p') 58 if self.file_path is not None: 59 file_handler = logging.FileHandler(self.file_path) 60 file_handler.setFormatter(formatter) 61 logger.addHandler(file_handler) 62 63 stream_handler = logging.StreamHandler() 64 stream_handler.setFormatter(formatter) 65 logger.addHandler(stream_handler) 66 logger.setLevel(logging.INFO) 67 68 return logger 69