|
| 1 | +import logging |
| 2 | +from wrapt import wrap_function_wrapper as _w |
| 3 | + |
| 4 | +from ddtrace import config |
| 5 | + |
| 6 | +from ...helpers import get_correlation_ids |
| 7 | +from ...utils.wrappers import unwrap as _u |
| 8 | + |
| 9 | +RECORD_ATTR_TRACE_ID = 'dd.trace_id' |
| 10 | +RECORD_ATTR_SPAN_ID = 'dd.span_id' |
| 11 | +RECORD_ATTR_VALUE_NULL = 0 |
| 12 | + |
| 13 | +config._add('logging', dict( |
| 14 | + tracer=None, # by default, override here for custom tracer |
| 15 | +)) |
| 16 | + |
| 17 | + |
| 18 | +def _w_makeRecord(func, instance, args, kwargs): |
| 19 | + record = func(*args, **kwargs) |
| 20 | + |
| 21 | + # add correlation identifiers to LogRecord |
| 22 | + trace_id, span_id = get_correlation_ids(tracer=config.logging.tracer) |
| 23 | + if trace_id and span_id: |
| 24 | + setattr(record, RECORD_ATTR_TRACE_ID, trace_id) |
| 25 | + setattr(record, RECORD_ATTR_SPAN_ID, span_id) |
| 26 | + else: |
| 27 | + setattr(record, RECORD_ATTR_TRACE_ID, RECORD_ATTR_VALUE_NULL) |
| 28 | + setattr(record, RECORD_ATTR_SPAN_ID, RECORD_ATTR_VALUE_NULL) |
| 29 | + |
| 30 | + return record |
| 31 | + |
| 32 | + |
| 33 | +def patch(): |
| 34 | + """ |
| 35 | + Patch ``logging`` module in the Python Standard Library for injection of |
| 36 | + tracer information by wrapping the base factory method ``Logger.makeRecord`` |
| 37 | + """ |
| 38 | + if getattr(logging, '_datadog_patch', False): |
| 39 | + return |
| 40 | + setattr(logging, '_datadog_patch', True) |
| 41 | + |
| 42 | + _w(logging.Logger, 'makeRecord', _w_makeRecord) |
| 43 | + |
| 44 | + |
| 45 | +def unpatch(): |
| 46 | + if getattr(logging, '_datadog_patch', False): |
| 47 | + setattr(logging, '_datadog_patch', False) |
| 48 | + |
| 49 | + _u(logging.Logger, 'makeRecord') |
0 commit comments