def format(self, record):
if self.debug and self.color:
if record.levelno >= logging.CRITICAL:
color = TEXT_RED
elif record.levelno >= logging.ERROR:
color = TEXT_RED
elif record.levelno >= logging.WARNING:
color = TEXT_YELLOW
elif record.levelno >= logging.INFO:
color = TEXT_GREEN
elif record.levelno >= logging.DEBUG:
color = TEXT_CYAN
else:
color = TEXT_NORMAL
record.levelname = "\x1b[%sm%s\x1b[%sm" % (color, record.levelname, TEXT_NORMAL)
return logging.Formatter.format(self, record)
python类WARNING的实例源码
def update_logging_settings(self, file_path=None, level=None, format=None):
"""
Update global logging. If None is set to the arguments, it will keep the previous setting.
Args:
file_path (str): It is Initialized to 'log.log'.
level (str): It can be 'error', 'warning' or 'info'. It is Initialized to 'error'.
format (str): It is Initialized to '%(asctime)s %(levelname)s %(message)s'.
"""
LOGGING_STRING_MAP = {'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR}
if file_path is not None:
self._logger_config['file_path'] = self._get_abs_path(file_path)
if level is not None:
self._logger_config['level'] = level
if format is not None:
self._logger_config['format'] = format
logger = logging.getLogger(Configuration.LOGGER_NAME)
log_file = logging.FileHandler(self._logger_config['file_path'])
logger.addHandler(log_file)
log_file.setFormatter(logging.Formatter(self._logger_config['format']))
logger.setLevel(LOGGING_STRING_MAP[self._logger_config['level']])
self._logger = logger
def configure_logging(info=False, debug=False):
"""Configure logging
The function configures log messages. By default, log messages
are sent to stderr. Set the parameter `debug` to activate the
debug mode.
:param debug: set the debug mode
"""
if info:
logging.basicConfig(level=logging.INFO,
format=LOG_FORMAT)
logging.getLogger('requests').setLevel(logging.WARNING)
logging.getLogger('urrlib3').setLevel(logging.WARNING)
logging.getLogger('elasticsearch').setLevel(logging.WARNING)
elif debug:
logging.basicConfig(level=logging.DEBUG,
format=DEBUG_LOG_FORMAT)
else:
logging.basicConfig(level=logging.WARNING,
format=LOG_FORMAT)
logging.getLogger('requests').setLevel(logging.WARNING)
logging.getLogger('urrlib3').setLevel(logging.WARNING)
logging.getLogger('elasticsearch').setLevel(logging.WARNING)
def test_warn_on_deprecated_flags(self):
sys.argv = ["[executable]",
"evaluate",
"--archive_file", "tests/fixtures/bidaf/serialization/model.tar.gz",
"--evaluation_data_file", "tests/fixtures/data/squad.json",
"--cuda_device", "-1"]
with self.assertLogs(level=logging.WARNING) as context:
main()
assert set(context.output) == {
'WARNING:allennlp.commands:Argument name --archive_file is deprecated '
'(and will likely go away at some point), please use --archive-file instead',
'WARNING:allennlp.commands:Argument name --evaluation_data_file is deprecated '
'(and will likely go away at some point), please use --evaluation-data-file instead',
'WARNING:allennlp.commands:Argument name --cuda_device is deprecated '
'(and will likely go away at some point), please use --cuda-device instead',
}
def get_fallback_logger(stream=None):
global _fallback_logger
if _fallback_logger:
return _fallback_logger
log_format = '%(asctime)s:%(levelname)s:%(message)s'
formatter = logging.Formatter(log_format)
level = logging.WARNING
handler = logging.StreamHandler(stream)
handler.setLevel(level)
handler.setFormatter(formatter)
logger = logging.Logger('powerline')
logger.setLevel(level)
logger.addHandler(handler)
_fallback_logger = PowerlineLogger(None, logger, '_fallback_')
return _fallback_logger
def draw(self, context):
layout = self.layout
scene = context.scene
for line in logList:
lines = line.split(":", 1)
if lines[0] == 'CRITICAL':
lineicon = 'RADIO'
elif lines[0] == 'ERROR':
lineicon = 'CANCEL'
elif lines[0] == 'WARNING':
lineicon = 'ERROR'
elif lines[0] == 'INFO':
lineicon = 'INFO'
else:
lineicon = 'TEXT'
layout.label(text = lines[1], icon = lineicon)
logList[:] = [] # Clear log list for next call (otherwise list is not updated when 'OK' button is not clicked)
# Export button
def get_logging_level(log_level):
logging_level = logging.INFO
if log_level == 'DEBUG':
logging_level = logging.DEBUG
elif log_level == 'INFO':
logging_level = logging.INFO
elif log_level == 'WARNING':
logging_level = logging.WARNING
elif log_level == 'ERROR':
logging_level = logging.ERROR
elif log_level == 'CRITICAL':
logging_level = logging.CRITICAL
else:
print('Unknown or unset logging level. Using INFO')
return logging_level
def debug(self, value):
"""
Sets the debug status.
:param value: The debug status, True or False.
:type: bool
"""
self.__debug = value
if self.__debug:
# if debug status is True, turn on debug logging
for _, logger in iteritems(self.logger):
logger.setLevel(logging.DEBUG)
# turn on httplib debug
httplib.HTTPConnection.debuglevel = 1
else:
# if debug status is False, turn off debug logging,
# setting log level to default `logging.WARNING`
for _, logger in iteritems(self.logger):
logger.setLevel(logging.WARNING)
# turn off httplib debug
httplib.HTTPConnection.debuglevel = 0
def set_up_logging(debug):
if debug:
logging_level = logging.DEBUG
else:
logging_level = logging.INFO
logging.basicConfig(format='%(asctime)s ~ %(levelname)-10s %(name)-25s %(message)s',
datefmt='%Y-%m-%d %H:%M',
level=logging_level)
logging.getLogger('telegram').setLevel(logging.WARNING)
logging.getLogger('requests').setLevel(logging.WARNING)
logging.getLogger('JobQueue').setLevel(logging.WARNING)
logging.addLevelName(logging.DEBUG, '?? DEBUG')
logging.addLevelName(logging.INFO, '?? INFO')
logging.addLevelName(logging.WARNING, '?? WARNING')
logging.addLevelName(logging.ERROR, '?? ERROR')
def debug(self, value):
"""
Sets the debug status.
:param value: The debug status, True or False.
:type: bool
"""
self.__debug = value
if self.__debug:
# if debug status is True, turn on debug logging
for _, logger in iteritems(self.logger):
logger.setLevel(logging.DEBUG)
# turn on httplib debug
httplib.HTTPConnection.debuglevel = 1
else:
# if debug status is False, turn off debug logging,
# setting log level to default `logging.WARNING`
for _, logger in iteritems(self.logger):
logger.setLevel(logging.WARNING)
# turn off httplib debug
httplib.HTTPConnection.debuglevel = 0
def configure_logging(info=False, debug=False):
"""Configure logging
The function configures log messages. By default, log messages
are sent to stderr. Set the parameter `debug` to activate the
debug mode.
:param debug: set the debug mode
"""
if info:
logging.basicConfig(level=logging.INFO,
format=LOG_FORMAT)
logging.getLogger('requests').setLevel(logging.WARNING)
logging.getLogger('urrlib3').setLevel(logging.WARNING)
logging.getLogger('elasticsearch').setLevel(logging.WARNING)
elif debug:
logging.basicConfig(level=logging.DEBUG,
format=DEBUG_LOG_FORMAT)
else:
logging.basicConfig(level=logging.WARNING,
format=LOG_FORMAT)
logging.getLogger('requests').setLevel(logging.WARNING)
logging.getLogger('urrlib3').setLevel(logging.WARNING)
logging.getLogger('elasticsearch').setLevel(logging.WARNING)
init.py 文件源码
项目:Grating_Advanced_Simulation_Platform
作者: GratingLaboratories
项目源码
文件源码
阅读 41
收藏 0
点赞 0
评论 0
def format(self, record):
stdout_template = '{levelname}' + Fore.RESET + '] {threadName}: ' + '{message}'
stdout_head = '[%s'
allFormats = {
logging.DEBUG: logging.StrFormatStyle(stdout_head % Fore.LIGHTBLUE_EX + stdout_template),
logging.INFO: logging.StrFormatStyle(stdout_head % Fore.GREEN + stdout_template),
logging.WARNING: logging.StrFormatStyle(stdout_head % Fore.LIGHTYELLOW_EX + stdout_template),
logging.ERROR: logging.StrFormatStyle(stdout_head % Fore.LIGHTRED_EX + stdout_template),
logging.CRITICAL: logging.StrFormatStyle(stdout_head % Fore.RED + stdout_template)
}
self._style = allFormats.get(record.levelno, logging.StrFormatStyle(logging._STYLES['{'][1]))
self._fmt = self._style._fmt
result = logging.Formatter.format(self, record)
return result
def debug(self, value):
"""
Sets the debug status.
:param value: The debug status, True or False.
:type: bool
"""
self.__debug = value
if self.__debug:
# if debug status is True, turn on debug logging
for _, logger in iteritems(self.logger):
logger.setLevel(logging.DEBUG)
# turn on httplib debug
httplib.HTTPConnection.debuglevel = 1
else:
# if debug status is False, turn off debug logging,
# setting log level to default `logging.WARNING`
for _, logger in iteritems(self.logger):
logger.setLevel(logging.WARNING)
# turn off httplib debug
httplib.HTTPConnection.debuglevel = 0
def format(self, record):
if self.debug and self.color:
if record.levelno >= logging.CRITICAL:
color = TEXT_RED
elif record.levelno >= logging.ERROR:
color = TEXT_RED
elif record.levelno >= logging.WARNING:
color = TEXT_YELLOW
elif record.levelno >= logging.INFO:
color = TEXT_GREEN
elif record.levelno >= logging.DEBUG:
color = TEXT_CYAN
else:
color = TEXT_NORMAL
record.levelname = "\x1b[%sm%s\x1b[%sm" % (color, record.levelname, TEXT_NORMAL)
return logging.Formatter.format(self, record)
def show_notices(printer=logger.log):
if Config.scout_notices:
for notice in Config.scout_notices:
try:
if isinstance(notice, str):
printer(logging.WARNING, notice)
else:
lvl = notice['level'].upper()
msg = notice['message']
if isinstance(lvl, str):
lvl = getattr(logging, lvl, logging.INFO)
printer(lvl, msg)
except KeyError:
printer(logging.WARNING, json.dumps(notice))
def clean_notices(notices):
cleaned = []
for notice in notices:
try:
if isinstance(notice, str):
cleaned.append({ "level": "WARNING", "message": notice })
else:
lvl = notice['level'].upper()
msg = notice['message']
cleaned.append({ "level": lvl, "message": msg })
except KeyError:
cleaned.append({ "level": "WARNING", "message": json.dumps(notice) })
except:
cleaned.append({ "level": "ERROR", "message": json.dumps(notice) })
return cleaned
def test_log_level_from_config(self):
cfg = {'verbose_level': 0}
self.assertEqual(logging.ERROR, logs.log_level_from_config(cfg))
cfg = {'verbose_level': 1}
self.assertEqual(logging.WARNING, logs.log_level_from_config(cfg))
cfg = {'verbose_level': 2}
self.assertEqual(logging.INFO, logs.log_level_from_config(cfg))
cfg = {'verbose_level': 3}
self.assertEqual(logging.DEBUG, logs.log_level_from_config(cfg))
cfg = {'verbose_level': 1, 'log_level': 'critical'}
self.assertEqual(logging.CRITICAL, logs.log_level_from_config(cfg))
cfg = {'verbose_level': 1, 'log_level': 'error'}
self.assertEqual(logging.ERROR, logs.log_level_from_config(cfg))
cfg = {'verbose_level': 1, 'log_level': 'warning'}
self.assertEqual(logging.WARNING, logs.log_level_from_config(cfg))
cfg = {'verbose_level': 1, 'log_level': 'info'}
self.assertEqual(logging.INFO, logs.log_level_from_config(cfg))
cfg = {'verbose_level': 1, 'log_level': 'debug'}
self.assertEqual(logging.DEBUG, logs.log_level_from_config(cfg))
cfg = {'verbose_level': 1, 'log_level': 'bogus'}
self.assertEqual(logging.WARNING, logs.log_level_from_config(cfg))
cfg = {'verbose_level': 1, 'log_level': 'info', 'debug': True}
self.assertEqual(logging.DEBUG, logs.log_level_from_config(cfg))
def __load_logging_level(self, config):
var = config.get_value('engine/replace-with-kanji-python', 'logging_level')
if var is None or var.get_type_string() != 's' or not var.get_string() in _name_to_logging_level:
level = 'WARNING'
if var:
config.unset('engine/replace-with-kanji-python', 'logging_level')
else:
level = var.get_string()
logger.info("logging_level: %s", level)
logging.getLogger().setLevel(_name_to_logging_level[level])
return level
def setup_logs(args):
"""
Initialize the api loggers.
Args:
args: dict containing the configuration options.
"""
flask_logging.create_logger = lambda app: use(app.logger_name)
if not args.get("debug", True):
set_level("werkzeug", logging.ERROR)
level = [logging.WARNING, logging.INFO, logging.DEBUG][
min(args.get("verbose", 1), 2)]
internal_error_log = ExceptionHandler()
internal_error_log.setLevel(logging.ERROR)
log.root.setLevel(level)
log.root.addHandler(internal_error_log)
if api.config.get_settings()["email"]["enable_email"]:
severe_error_log = SevereHandler()
severe_error_log.setLevel(logging.CRITICAL)
log.root.addHandler(severe_error_log)
stats_log = StatsHandler()
stats_log.setLevel(logging.INFO)
log.root.addHandler(stats_log)
def _cli_argument_parser():
argp = argparse.ArgumentParser(
description='Produce Lilypond documentation')
argp.add_argument(
'path', metavar='PATH',
help='The file or directory to parse')
argp.add_argument(
'--output', '-o', metavar='FILE',
help='The output file. If not given, prints to standard output')
argp.add_argument(
'--trace-parser', action='store_true', dest='trace_parser',
help='Print debug information from the parser')
argp.add_argument(
'-d', '--debug',
help="Detailed debugging information",
action="store_const", dest="loglevel", const=logging.DEBUG,
default=logging.WARNING)
argp.add_argument(
'-v', '--verbose',
help="Verbose output",
action="store_const", dest="loglevel", const=logging.INFO)
return argp