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 |
Sapan Bhatia | b734774 | 2017-09-22 09:41:56 -0700 | [diff] [blame] | 45 | import inspect |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 46 | |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 47 | PROCESSOR_MAP = { |
Sapan Bhatia | f188c08 | 2018-02-01 11:33:16 -0500 | [diff] [blame] | 48 | 'StreamHandler': structlog.dev.ConsoleRenderer(colors=True, force_colors=True), |
Sapan Bhatia | 5ec80d3 | 2017-10-23 11:59:58 -0400 | [diff] [blame] | 49 | 'LogstashHandler': structlog.processors.JSONRenderer(), |
| 50 | 'RotatingFileHandler': structlog.processors.JSONRenderer() |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 51 | } |
| 52 | |
Sapan Bhatia | b734774 | 2017-09-22 09:41:56 -0700 | [diff] [blame] | 53 | |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 54 | class FormatterFactory: |
| 55 | def __init__(self, handler_name): |
| 56 | self.handler_name = handler_name |
| 57 | |
| 58 | def __call__(self): |
| 59 | try: |
| 60 | processor = PROCESSOR_MAP[self.handler_name] |
| 61 | except KeyError: |
| 62 | processor = structlog.processors.KeyValueRenderer() |
| 63 | |
| 64 | formatter = structlog.stdlib.ProcessorFormatter(processor) |
| 65 | |
| 66 | return formatter |
| 67 | |
| 68 | |
| 69 | class XOSLoggerFactory: |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 70 | def __init__(self, handlers): |
| 71 | self.handlers = handlers |
| 72 | |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 73 | def __call__(self): |
Sapan Bhatia | 5ec80d3 | 2017-10-23 11:59:58 -0400 | [diff] [blame] | 74 | base_logger = logging.getLogger("multistructlog") |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 75 | base_logger.handlers = [] |
| 76 | for h in self.handlers: |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 77 | formatter = FormatterFactory(h.__class__.__name__)() |
| 78 | h.setFormatter(formatter) |
| 79 | base_logger.addHandler(h) |
| 80 | |
| 81 | self.logger = base_logger |
| 82 | return self.logger |
| 83 | |
| 84 | |
| 85 | """ We expose the Structlog logging interface directly. This should allow callers to |
Sapan Bhatia | b734774 | 2017-09-22 09:41:56 -0700 | [diff] [blame] | 86 | bind contexts incrementally and configure and use other features of structlog directly |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 87 | |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 88 | 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] | 89 | """ |
| 90 | |
Sapan Bhatia | 74cd1e4 | 2017-08-14 02:00:04 -0400 | [diff] [blame] | 91 | CURRENT_LOGGER = None |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 92 | CURRENT_LOGGER_PARMS = None |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 93 | |
Sapan Bhatia | b734774 | 2017-09-22 09:41:56 -0700 | [diff] [blame] | 94 | |
| 95 | def create_logger(_config=None, extra_processors=[], |
| 96 | force_create=False, level=None): |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 97 | """ |
| 98 | Args: |
| 99 | _config (dict): The standard config for Python's logging module |
| 100 | extra_processors(dict): Custom structlog processors |
Sapan Bhatia | b734774 | 2017-09-22 09:41:56 -0700 | [diff] [blame] | 101 | force_create(bool): Forces creation of the logger |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 102 | level(logging.loglevel): Overrides logging level |
| 103 | |
| 104 | Returns: |
| 105 | log: structlog logger |
| 106 | """ |
| 107 | |
| 108 | first_entry_elts = ['Starting'] |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 109 | |
| 110 | """Inherit base options from config""" |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 111 | if _config: |
Sapan Bhatia | e437cf4 | 2017-08-21 22:41:29 -0400 | [diff] [blame] | 112 | logging_config = copy.deepcopy(_config) |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 113 | else: |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 114 | first_entry_elts.append('Config is empty') |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 115 | logging_config = {'version': 1} |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 116 | |
Sapan Bhatia | b734774 | 2017-09-22 09:41:56 -0700 | [diff] [blame] | 117 | """Check if a logger with this configuration has already been created, if so, return that logger |
Sapan Bhatia | 74cd1e4 | 2017-08-14 02:00:04 -0400 | [diff] [blame] | 118 | instead of creating a new one""" |
| 119 | global CURRENT_LOGGER |
| 120 | global CURRENT_LOGGER_PARMS |
Sapan Bhatia | b734774 | 2017-09-22 09:41:56 -0700 | [diff] [blame] | 121 | if CURRENT_LOGGER and CURRENT_LOGGER_PARMS == ( |
| 122 | logging_config, extra_processors, level) and not force_create: |
Sapan Bhatia | 74cd1e4 | 2017-08-14 02:00:04 -0400 | [diff] [blame] | 123 | return CURRENT_LOGGER |
Sapan Bhatia | b734774 | 2017-09-22 09:41:56 -0700 | [diff] [blame] | 124 | |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 125 | if level: |
| 126 | try: |
Sapan Bhatia | b734774 | 2017-09-22 09:41:56 -0700 | [diff] [blame] | 127 | for k, v in logging_config['loggers'].iteritems(): |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 128 | v['level'] = level |
| 129 | except KeyError: |
| 130 | first_entry_elts.append('Level override failed') |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 131 | |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 132 | logging.config.dictConfig(logging_config) |
| 133 | |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 134 | processors = copy.copy(extra_processors) |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 135 | processors.extend([ |
| 136 | structlog.processors.StackInfoRenderer(), |
| 137 | structlog.processors.format_exc_info, |
| 138 | structlog.stdlib.ProcessorFormatter.wrap_for_formatter |
| 139 | ]) |
Sapan Bhatia | b734774 | 2017-09-22 09:41:56 -0700 | [diff] [blame] | 140 | |
Sapan Bhatia | 3ec782d | 2017-10-31 14:05:58 -0400 | [diff] [blame] | 141 | |
| 142 | handlers = logging.getLogger('multistructlog').handlers |
Sapan Bhatia | b734774 | 2017-09-22 09:41:56 -0700 | [diff] [blame] | 143 | |
Sapan Bhatia | 3ec782d | 2017-10-31 14:05:58 -0400 | [diff] [blame] | 144 | if not handlers: |
| 145 | caller = inspect.stack()[1] |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 146 | |
Sapan Bhatia | 3ec782d | 2017-10-31 14:05:58 -0400 | [diff] [blame] | 147 | try: |
| 148 | filename = inspect.getmodule(caller[0]).__name__ |
| 149 | except AttributeError: |
| 150 | filename = '/tmp/multistructlog' |
| 151 | |
| 152 | handlers = [ |
| 153 | logging.StreamHandler(sys.stdout), |
| 154 | logging.handlers.RotatingFileHandler( |
| 155 | filename=filename, |
| 156 | maxBytes=10485760, |
| 157 | backupCount=1) |
| 158 | ] |
| 159 | |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 160 | factory = XOSLoggerFactory(handlers) |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 161 | |
| 162 | structlog.configure( |
| 163 | processors=processors, |
| 164 | logger_factory=factory, |
| 165 | ) |
| 166 | |
| 167 | log = structlog.get_logger() |
| 168 | first_entry = '. '.join(first_entry_elts) |
Sapan Bhatia | b734774 | 2017-09-22 09:41:56 -0700 | [diff] [blame] | 169 | log.info(first_entry, level_override=level, **logging_config) |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 170 | |
Sapan Bhatia | 74cd1e4 | 2017-08-14 02:00:04 -0400 | [diff] [blame] | 171 | CURRENT_LOGGER = log |
Sapan Bhatia | 9ec41c2 | 2017-08-24 05:31:28 -0400 | [diff] [blame] | 172 | CURRENT_LOGGER_PARMS = (logging_config, extra_processors, level) |
Varun Belur | f81a5fc | 2017-08-11 16:52:59 -0700 | [diff] [blame] | 173 | return log |
Sapan Bhatia | 74cd1e4 | 2017-08-14 02:00:04 -0400 | [diff] [blame] | 174 | |
Sapan Bhatia | b734774 | 2017-09-22 09:41:56 -0700 | [diff] [blame] | 175 | |
Sapan Bhatia | 74cd1e4 | 2017-08-14 02:00:04 -0400 | [diff] [blame] | 176 | if __name__ == '__main__': |
Sapan Bhatia | b734774 | 2017-09-22 09:41:56 -0700 | [diff] [blame] | 177 | l = create_logger( |
| 178 | {'version': 2, 'loggers': {'': {'level': 'INFO'}}}, level="INFO") |
Sapan Bhatia | 74cd1e4 | 2017-08-14 02:00:04 -0400 | [diff] [blame] | 179 | l.info("Test OK") |