Formatter which formats messages as GELF 2 - https://www.graylog.org/resources/gelf-2/ For example: LOG.info('Hello world', extra={'_id': 1, '_path': '/fooo'}) Result: { "version": "1.1", "level": 6, "timestamp": 1426590583,
| 204 | |
| 205 | |
| 206 | class GelfLogFormatter(BaseExtraLogFormatter): |
| 207 | """ |
| 208 | Formatter which formats messages as GELF 2 - https://www.graylog.org/resources/gelf-2/ |
| 209 | |
| 210 | For example: |
| 211 | |
| 212 | LOG.info('Hello world', extra={'_id': 1, '_path': '/fooo'}) |
| 213 | |
| 214 | Result: |
| 215 | |
| 216 | { |
| 217 | "version": "1.1", |
| 218 | "level": 6, |
| 219 | "timestamp": 1426590583, |
| 220 | "_python": { |
| 221 | "process": 11277, |
| 222 | "module": "__init__", |
| 223 | "funcName": "db_setup", |
| 224 | "processName": "MainProcess", |
| 225 | "lineno": 28, |
| 226 | "filename": "__init__.py" |
| 227 | }, |
| 228 | "host": "vagrant-ubuntu-trusty-64", |
| 229 | "full_message": "2015-03-17 11:09:43,507 INFO [-] Hello world", |
| 230 | "_path": "/fooo", |
| 231 | "_id": 1, |
| 232 | "short_message": "Hello world" |
| 233 | } |
| 234 | """ |
| 235 | |
| 236 | # Maps python log level to syslog / gelf log level |
| 237 | PYTHON_TO_GELF_LEVEL_MAP = { |
| 238 | 50: 2, # critical -> critical |
| 239 | 40: 3, # error -> error |
| 240 | 30: 4, # warning -> warning |
| 241 | 20: 6, # info -> informational |
| 242 | 10: 7, # debug -> debug |
| 243 | 0: 6, # notset -> information |
| 244 | } |
| 245 | DEFAULT_LOG_LEVEL = 6 # info |
| 246 | |
| 247 | def format(self, record): |
| 248 | attributes = self._get_extra_attributes(record=record) |
| 249 | attributes = self._format_extra_attributes(attributes=attributes) |
| 250 | |
| 251 | msg = record.msg |
| 252 | exc_info = record.exc_info |
| 253 | time_now_float = record.created |
| 254 | time_now_sec = int(time_now_float) |
| 255 | level = self.PYTHON_TO_GELF_LEVEL_MAP.get( |
| 256 | record.levelno, self.DEFAULT_LOG_LEVEL |
| 257 | ) |
| 258 | |
| 259 | common_attributes = self._get_common_extra_attributes(record=record) |
| 260 | full_msg = super(GelfLogFormatter, self).format(record) |
| 261 | |
| 262 | data = { |
| 263 | "version": GELF_SPEC_VERSION, |
no outgoing calls