|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import logging.handlers |
| 4 | +import sys |
| 5 | +import shutil |
| 6 | + |
| 7 | +from datetime import datetime |
| 8 | + |
| 9 | +from reframe.settings import settings |
| 10 | +from reframe.core.exceptions import ConfigurationError, ReframeError |
| 11 | + |
| 12 | +# Reframe's log levels |
| 13 | +CRITICAL = 50 |
| 14 | +ERROR = 40 |
| 15 | +WARNING = 30 |
| 16 | +INFO = 20 |
| 17 | +VERBOSE = 19 |
| 18 | +DEBUG = 10 |
| 19 | +NOTSET = 0 |
| 20 | + |
| 21 | + |
| 22 | +_log_level_names = { |
| 23 | + CRITICAL : 'critical', |
| 24 | + ERROR : 'error', |
| 25 | + WARNING : 'warning', |
| 26 | + INFO : 'info', |
| 27 | + VERBOSE : 'verbose', |
| 28 | + DEBUG : 'debug', |
| 29 | + NOTSET : 'undefined' |
| 30 | +} |
| 31 | + |
| 32 | +_log_level_values = { |
| 33 | + 'critical' : CRITICAL, |
| 34 | + 'error' : ERROR, |
| 35 | + 'warning' : WARNING, |
| 36 | + 'info' : INFO, |
| 37 | + 'verbose' : VERBOSE, |
| 38 | + 'debug' : DEBUG, |
| 39 | + 'undefined' : NOTSET, |
| 40 | + 'notset' : NOTSET |
| 41 | +} |
| 42 | + |
| 43 | +def _check_level(level): |
| 44 | + if isinstance(level, int): |
| 45 | + ret = level |
| 46 | + elif isinstance(level, str): |
| 47 | + norm_level = level.lower() |
| 48 | + if norm_level not in _log_level_values: |
| 49 | + raise ReframeError('logger level %s not available' % level) |
| 50 | + else: |
| 51 | + ret = _log_level_values[norm_level] |
| 52 | + else: |
| 53 | + raise TypeError('logger level %s not an int or a valid string' % level) |
| 54 | + |
| 55 | + return ret |
| 56 | + |
| 57 | + |
| 58 | +# Redefine handlers so as to use our levels |
| 59 | + |
| 60 | +class Handler(logging.Handler): |
| 61 | + def setLevel(self, level): |
| 62 | + self.level = _check_level(level) |
| 63 | + |
| 64 | + |
| 65 | +class StreamHandler(Handler, logging.StreamHandler): |
| 66 | + pass |
| 67 | + |
| 68 | + |
| 69 | +class RotatingFileHandler(Handler, logging.handlers.RotatingFileHandler): |
| 70 | + pass |
| 71 | + |
| 72 | + |
| 73 | +class FileHandler(Handler, logging.FileHandler): |
| 74 | + pass |
| 75 | + |
| 76 | + |
| 77 | +class NullHandler(Handler, logging.NullHandler): |
| 78 | + pass |
| 79 | + |
| 80 | + |
| 81 | +def load_from_dict(logging_config): |
| 82 | + if not isinstance(logging_config, dict): |
| 83 | + raise ConfigurationError('logging configuration is not a dict') |
| 84 | + |
| 85 | + level = logging_config.get('level', 'info').lower() |
| 86 | + handlers_dict = logging_config.get('handlers', None) |
| 87 | + |
| 88 | + # if not handlers_dict: |
| 89 | + # raise ConfigurationError('no entry for handlers was found') |
| 90 | + |
| 91 | + logger = Logger('reframe') |
| 92 | + logger.setLevel(_log_level_values[level]) |
| 93 | + |
| 94 | + for handler in _extract_handlers(handlers_dict): |
| 95 | + logger.addHandler(handler) |
| 96 | + |
| 97 | + return logger |
| 98 | + |
| 99 | + |
| 100 | +def _extract_handlers(handlers_dict): |
| 101 | + handlers = [] |
| 102 | + if not handlers_dict: |
| 103 | + raise ConfigurationError('no handlers are defined for logger') |
| 104 | + |
| 105 | + for filename, handler_config in handlers_dict.items(): |
| 106 | + if not isinstance(handler_config, dict): |
| 107 | + raise ConfigurationError( |
| 108 | + 'handler %s is not a dictionary' % filename |
| 109 | + ) |
| 110 | + |
| 111 | + level = handler_config.get('level', 'debug').lower() |
| 112 | + fmt = handler_config.get('format', '%(message)s') |
| 113 | + datefmt = handler_config.get('datefmt', '%FT%T') |
| 114 | + append = handler_config.get('append', False) |
| 115 | + timestamp = handler_config.get('timestamp', None) |
| 116 | + |
| 117 | + if filename == '&1': |
| 118 | + hdlr = StreamHandler(stream=sys.stdout) |
| 119 | + elif filename == '&2': |
| 120 | + hdlr = StreamHandler(stream=sys.stderr) |
| 121 | + else: |
| 122 | + if timestamp: |
| 123 | + basename, ext = os.path.splitext(filename) |
| 124 | + filename = '%s_%s%s' % ( |
| 125 | + basename, datetime.now().strftime(timestamp), ext |
| 126 | + ) |
| 127 | + |
| 128 | + hdlr = RotatingFileHandler( |
| 129 | + filename, mode='a+' if append else 'w+' |
| 130 | + ) |
| 131 | + |
| 132 | + hdlr.setFormatter(logging.Formatter(fmt=fmt, datefmt=datefmt)) |
| 133 | + hdlr.setLevel(level) |
| 134 | + handlers.append(hdlr) |
| 135 | + |
| 136 | + return handlers |
| 137 | + |
| 138 | + |
| 139 | +class Logger(logging.Logger): |
| 140 | + def __init__(self, name, level=logging.NOTSET): |
| 141 | + # We will set the logger level ourselves so as to bypass the base class' |
| 142 | + # check |
| 143 | + super().__init__(name, logging.NOTSET) |
| 144 | + self.level = _check_level(level) |
| 145 | + self.check = None |
| 146 | + |
| 147 | + |
| 148 | + def setLevel(self, level): |
| 149 | + self.level = _check_level(level) |
| 150 | + |
| 151 | + |
| 152 | + def makeRecord(self, name, level, fn, lno, msg, args, exc_info, |
| 153 | + func=None, extra=None, sinfo=None): |
| 154 | + # Setup dynamic fields of the check |
| 155 | + if self.check and self.check.job: |
| 156 | + extra['check_jobid'] = self.check.job.jobid |
| 157 | + |
| 158 | + record = super().makeRecord(name, level, fn, lno, msg, args, exc_info, |
| 159 | + func, extra, sinfo) |
| 160 | + try: |
| 161 | + # Fill in our name for the record |
| 162 | + record.levelname = _log_level_names[level] |
| 163 | + except KeyError: |
| 164 | + # Go with the default level name of Python logging |
| 165 | + pass |
| 166 | + |
| 167 | + return record |
| 168 | + |
| 169 | + |
| 170 | + # Override all the convenience logging functions, because we want to make |
| 171 | + # sure that they map to our level definitions |
| 172 | + |
| 173 | + def critical(self, msg, *args, **kwargs): |
| 174 | + return self.log(CRITICAL, msg, *args, **kwargs) |
| 175 | + |
| 176 | + |
| 177 | + def error(self, msg, *args, **kwargs): |
| 178 | + return self.log(ERROR, msg, *args, **kwargs) |
| 179 | + |
| 180 | + |
| 181 | + def warning(self, msg, *args, **kwargs): |
| 182 | + return self.log(WARNING, msg, *args, **kwargs) |
| 183 | + |
| 184 | + |
| 185 | + def info(self, msg, *args, **kwargs): |
| 186 | + return self.log(INFO, msg, *args, **kwargs) |
| 187 | + |
| 188 | + |
| 189 | + def verbose(self, message, *args, **kwargs): |
| 190 | + self.log(VERBOSE, message, *args, **kwargs) |
| 191 | + |
| 192 | + |
| 193 | + def debug(self, message, *args, **kwargs): |
| 194 | + self.log(DEBUG, message, *args, **kwargs) |
| 195 | + |
| 196 | + |
| 197 | +class LoggerAdapter(logging.LoggerAdapter): |
| 198 | + def __init__(self, logger = None, check = None): |
| 199 | + super().__init__( |
| 200 | + logger, |
| 201 | + { |
| 202 | + 'check_name' : check.name if check else 'reframe', |
| 203 | + 'check_jobid' : '-1' |
| 204 | + } |
| 205 | + ) |
| 206 | + if self.logger: |
| 207 | + self.logger.check = check |
| 208 | + |
| 209 | + |
| 210 | + def setLevel(self, level): |
| 211 | + if self.logger: |
| 212 | + super().setLevel(level) |
| 213 | + |
| 214 | + |
| 215 | + # Override log() function to treat `None` loggers |
| 216 | + def log(self, level, msg, *args, **kwargs): |
| 217 | + if self.logger: |
| 218 | + super().log(level, msg, *args, **kwargs) |
| 219 | + |
| 220 | + |
| 221 | + def verbose(self, message, *args, **kwargs): |
| 222 | + self.log(VERBOSE, message, *args, **kwargs) |
| 223 | + |
| 224 | + |
| 225 | +# A logger that doesn't log anything |
| 226 | +null_logger = LoggerAdapter() |
| 227 | + |
| 228 | +_logger = None |
| 229 | +_frontend_logger = null_logger |
| 230 | + |
| 231 | +def configure_logging(config): |
| 232 | + global _logger |
| 233 | + global _frontend_logger |
| 234 | + |
| 235 | + if config == None: |
| 236 | + _logger = None |
| 237 | + _frontend_logger = null_logger |
| 238 | + return |
| 239 | + |
| 240 | + _logger = load_from_dict(config) |
| 241 | + _frontend_logger = LoggerAdapter(_logger) |
| 242 | + |
| 243 | + |
| 244 | +def save_log_files(dest): |
| 245 | + os.makedirs(dest, exist_ok=True) |
| 246 | + for hdlr in _logger.handlers: |
| 247 | + if isinstance(hdlr, logging.FileHandler): |
| 248 | + shutil.copy(hdlr.baseFilename, dest, follow_symlinks=True) |
| 249 | + |
| 250 | +def getlogger(logger_kind, *args, **kwargs): |
| 251 | + if logger_kind == 'frontend': |
| 252 | + return _frontend_logger |
| 253 | + elif logger_kind == 'check': |
| 254 | + return LoggerAdapter(_logger, *args, **kwargs) |
| 255 | + else: |
| 256 | + raise ReframeError('unknown kind of logger: %s' % logger_kind) |
0 commit comments