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