Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 1 | # Copyright 2017-present Open Networking Foundation |
| 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 | multistructlog logging module |
| 17 | |
| 18 | This module enables structured data to be logged to a single destination, or to |
| 19 | multiple destinations simulataneously. The API consists of a single function: |
| 20 | create_logger, which returns a structlog object. You can invoke it as follows: |
| 21 | |
| 22 | log = logger.create_logger(xos_config, level=logging.INFO) |
| 23 | log.info('Entered function', name = '%s' % fn_name) |
| 24 | |
| 25 | The default handlers in XOS are the console and Logstash. You can override the |
| 26 | handlers, structlog's processors, or anything else by adding keyword arguments |
| 27 | to create_logger: |
| 28 | |
| 29 | log = logger.create_logger(xos_config, level=logging.INFO, |
| 30 | handlers=[logging.StreamHandler(sys.stdout), |
| 31 | logstash.LogstashHandler('somehost', 5617, version=1)]) |
| 32 | |
| 33 | Each handler depends on a specific renderer (e.g. Logstash needs JSON and |
| 34 | stdout needs ConsoleRenderer) but a structlog instance can enchain only one |
Sapan Bhatia | 74cd1e4 | 2017-08-14 02:00:04 -0400 | [diff] [blame] | 35 | renderer. For this reason, we apply renderers at the logging layer, as |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 36 | logging formatters. |
| 37 | """ |
| 38 | |
| 39 | import logging |
| 40 | import logging.config |
| 41 | import logstash |
| 42 | import structlog |
| 43 | import sys |
| 44 | import copy |
| 45 | |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 46 | PROCESSOR_MAP = { |
| 47 | 'StreamHandler': structlog.dev.ConsoleRenderer(), |
| 48 | 'LogstashHandler': structlog.processors.JSONRenderer(), |
| 49 | } |
| 50 | |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 51 | class FormatterFactory: |
| 52 | def __init__(self, handler_name): |
| 53 | self.handler_name = handler_name |
| 54 | |
| 55 | def __call__(self): |
| 56 | try: |
| 57 | processor = PROCESSOR_MAP[self.handler_name] |
| 58 | except KeyError: |
| 59 | processor = structlog.processors.KeyValueRenderer() |
| 60 | |
| 61 | formatter = structlog.stdlib.ProcessorFormatter(processor) |
| 62 | |
| 63 | return formatter |
| 64 | |
| 65 | |
| 66 | class XOSLoggerFactory: |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 67 | def __init__(self, handlers): |
| 68 | self.handlers = handlers |
| 69 | |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 70 | def __call__(self): |
| 71 | base_logger = logging.getLogger() |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 72 | base_logger.handlers = [] |
| 73 | for h in self.handlers: |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 74 | formatter = FormatterFactory(h.__class__.__name__)() |
| 75 | h.setFormatter(formatter) |
| 76 | base_logger.addHandler(h) |
| 77 | |
| 78 | self.logger = base_logger |
| 79 | return self.logger |
| 80 | |
| 81 | |
| 82 | """ We expose the Structlog logging interface directly. This should allow callers to |
| 83 | bind contexts incrementally and configure and use other features of structlog directly |
| 84 | |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 85 | The use of structlog in Chameleon was used for reference when writing this code. |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 86 | """ |
| 87 | |
Sapan Bhatia | 74cd1e4 | 2017-08-14 02:00:04 -0400 | [diff] [blame] | 88 | CURRENT_LOGGER = None |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 89 | CURRENT_LOGGER_PARMS = None |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 90 | |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 91 | def create_logger(_config=None, extra_processors=[], force_create=False, level=None): |
| 92 | """ |
| 93 | Args: |
| 94 | _config (dict): The standard config for Python's logging module |
| 95 | extra_processors(dict): Custom structlog processors |
| 96 | force_create(bool): Forces creation of the logger |
| 97 | level(logging.loglevel): Overrides logging level |
| 98 | |
| 99 | Returns: |
| 100 | log: structlog logger |
| 101 | """ |
| 102 | |
| 103 | first_entry_elts = ['Starting'] |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 104 | |
| 105 | """Inherit base options from config""" |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 106 | if _config: |
Sapan Bhatia | e437cf4 | 2017-08-21 22:41:29 -0400 | [diff] [blame] | 107 | logging_config = copy.deepcopy(_config) |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 108 | else: |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 109 | first_entry_elts.append('Config is empty') |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 110 | logging_config = {'version': 1} |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 111 | |
Sapan Bhatia | 74cd1e4 | 2017-08-14 02:00:04 -0400 | [diff] [blame] | 112 | """Check if a logger with this configuration has already been created, if so, return that logger |
| 113 | instead of creating a new one""" |
| 114 | global CURRENT_LOGGER |
| 115 | global CURRENT_LOGGER_PARMS |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 116 | if CURRENT_LOGGER and CURRENT_LOGGER_PARMS == (logging_config, extra_processors, level) and not force_create: |
Sapan Bhatia | 74cd1e4 | 2017-08-14 02:00:04 -0400 | [diff] [blame] | 117 | return CURRENT_LOGGER |
| 118 | |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 119 | if level: |
| 120 | try: |
| 121 | for k,v in logging_config['loggers'].iteritems(): |
| 122 | v['level'] = level |
| 123 | except KeyError: |
| 124 | first_entry_elts.append('Level override failed') |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 125 | |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 126 | logging.config.dictConfig(logging_config) |
| 127 | |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 128 | processors = copy.copy(extra_processors) |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 129 | processors.extend([ |
| 130 | structlog.processors.StackInfoRenderer(), |
| 131 | structlog.processors.format_exc_info, |
| 132 | structlog.stdlib.ProcessorFormatter.wrap_for_formatter |
| 133 | ]) |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 134 | |
| 135 | default_handlers = [ |
| 136 | logging.StreamHandler(sys.stdout), |
| 137 | logstash.LogstashHandler('localhost', 5617, version=1) |
| 138 | ] |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 139 | |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 140 | configured_handlers = logging.getLogger().handlers |
| 141 | handlers = configured_handlers if configured_handlers else default_handlers |
| 142 | factory = XOSLoggerFactory(handlers) |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 143 | |
| 144 | structlog.configure( |
| 145 | processors=processors, |
| 146 | logger_factory=factory, |
| 147 | ) |
| 148 | |
| 149 | log = structlog.get_logger() |
| 150 | first_entry = '. '.join(first_entry_elts) |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 151 | log.info(first_entry, level_override=level,**logging_config) |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 152 | |
Sapan Bhatia | 74cd1e4 | 2017-08-14 02:00:04 -0400 | [diff] [blame] | 153 | CURRENT_LOGGER = log |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 154 | CURRENT_LOGGER_PARMS = (logging_config, extra_processors, level) |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 155 | return log |
Sapan Bhatia | 74cd1e4 | 2017-08-14 02:00:04 -0400 | [diff] [blame] | 156 | |
| 157 | if __name__ == '__main__': |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 158 | l = create_logger({'version': 2, 'loggers':{'':{'level': 'INFO'}}}, level="INFO") |
Sapan Bhatia | 74cd1e4 | 2017-08-14 02:00:04 -0400 | [diff] [blame] | 159 | l.info("Test OK") |