Add option to use JSON formatter

This adds the use_json option, which will use the JSON formatter
instead of the deafult ContextFormatter if set.

Closes-Bug: #1729331
Change-Id: I1b7b7b9e66215e8e1c59a2c0a37cb0abaebf228a
This commit is contained in:
Juan Antonio Osorio Robles 2017-11-06 07:46:26 +00:00
parent 4302d98b5c
commit 215cc3a8ec
3 changed files with 23 additions and 5 deletions

View File

@ -97,6 +97,10 @@ logging_cli_opts = [
default='LOG_USER',
help='Syslog facility to receive log lines. '
+ _IGNORE_MESSAGE),
cfg.BoolOpt('use-json',
default=False,
help='Use JSON formatting for logging. '
+ _IGNORE_MESSAGE),
]
generic_log_opts = [

View File

@ -383,11 +383,15 @@ def _setup_logging_from_conf(conf, project, version):
log_root.addHandler(syslog_handler)
datefmt = conf.log_date_format
for handler in log_root.handlers:
handler.setFormatter(formatters.ContextFormatter(project=project,
version=version,
datefmt=datefmt,
config=conf))
if not conf.use_json:
for handler in log_root.handlers:
handler.setFormatter(formatters.ContextFormatter(project=project,
version=version,
datefmt=datefmt,
config=conf))
else:
for handler in log_root.handlers:
handler.setFormatter(formatters.JSONFormatter(datefmt=datefmt))
_refresh_root_level(conf.debug)
for pair in conf.default_log_levels:

View File

@ -1496,6 +1496,7 @@ class LogConfigOptsTestCase(BaseTestCase):
self.CONF.log_date_format)
self.assertEqual(False, self.CONF.use_syslog)
self.assertEqual(False, self.CONF.use_json)
def test_log_file(self):
log_file = '/some/path/foo-bar.log'
@ -1553,6 +1554,15 @@ class LogConfigOptsTestCase(BaseTestCase):
self.assertIsInstance(formatter,
formatters.ContextFormatter)
def test_json_formatter(self):
self.CONF(['--use-json'])
log._setup_logging_from_conf(self.CONF, 'test', 'test')
logger = log._loggers[None].logger
for handler in logger.handlers:
formatter = handler.formatter
self.assertIsInstance(formatter,
formatters.JSONFormatter)
def test_handlers_cleanup(self):
"""Test that all old handlers get removed from log_root."""
old_handlers = [log.handlers.ColorHandler(),