github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/sawtooth-core-master/validator/sawtooth_validator/server/log.py (about) 1 # Copyright 2016 Intel Corporation 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.config 18 import sys 19 import os 20 21 from colorlog import ColoredFormatter 22 23 24 class LogWriter(object): 25 def __init__(self, logger, level): 26 self.logger = logger 27 self.level = level 28 29 def write(self, line): 30 if line != '\n': 31 self.logger.log(self.level, line.rstrip()) 32 33 34 def create_console_handler(verbose_level): 35 clog = logging.StreamHandler() 36 formatter = ColoredFormatter( 37 "%(log_color)s[%(asctime)s.%(msecs)03d " 38 "%(levelname)-8s %(module)s]%(reset)s " 39 "%(white)s%(message)s", 40 datefmt="%Y-%m-%d %H:%M:%S", 41 reset=True, 42 log_colors={ 43 'DEBUG': 'cyan', 44 'INFO': 'green', 45 'WARNING': 'yellow', 46 'ERROR': 'red', 47 'CRITICAL': 'red', 48 }) 49 50 clog.setFormatter(formatter) 51 52 if verbose_level == 0: 53 clog.setLevel(logging.WARN) 54 elif verbose_level == 1: 55 clog.setLevel(logging.INFO) 56 else: 57 clog.setLevel(logging.DEBUG) 58 59 return clog 60 61 62 def init_console_logging(verbose_level=2, capture_std_output=False): 63 logger = logging.getLogger() 64 logger.setLevel(logging.DEBUG) 65 66 logger.addHandler(create_console_handler(verbose_level)) 67 68 if capture_std_output: 69 sys.stdout = LogWriter(logging.getLogger("STDOUT"), logging.INFO) 70 sys.stderr = LogWriter(logging.getLogger("STDERR"), logging.ERROR) 71 72 73 def log_configuration(log_config=None, log_dir=None, name=None): 74 if log_config is not None: 75 logging.config.dictConfig(log_config) 76 else: 77 log_filename = os.path.join(log_dir, name) 78 debug_handler = logging.FileHandler(log_filename + "-debug.log") 79 debug_handler.setFormatter(logging.Formatter( 80 '[%(asctime)s.%(msecs)03d [%(threadName)s] %(module)s' 81 ' %(levelname)s] %(message)s', "%H:%M:%S")) 82 debug_handler.setLevel(logging.DEBUG) 83 84 error_handler = logging.FileHandler(log_filename + "-error.log") 85 error_handler.setFormatter(logging.Formatter( 86 '[%(asctime)s.%(msecs)03d [%(threadName)s] %(module)s' 87 ' %(levelname)s] %(message)s', "%H:%M:%S")) 88 error_handler.setLevel(logging.ERROR) 89 90 logging.getLogger().addHandler(error_handler) 91 logging.getLogger().addHandler(debug_handler)