diff --git a/ddtrace/_logger.py b/ddtrace/_logger.py index 631e9d97e4a..5bde0c11da2 100644 --- a/ddtrace/_logger.py +++ b/ddtrace/_logger.py @@ -110,6 +110,14 @@ def _add_file_handler( return ddtrace_file_handler +def set_log_formatting(): + # type: () -> None + """Sets the log format for the ddtrace logger.""" + ddtrace_logger = logging.getLogger("ddtrace") + for handler in ddtrace_logger.handlers: + handler.setFormatter(logging.Formatter(DD_LOG_FORMAT)) + + def get_log_injection_state(raw_config: Optional[str]) -> bool: """Returns the current log injection state.""" if raw_config: diff --git a/ddtrace/contrib/internal/logging/patch.py b/ddtrace/contrib/internal/logging/patch.py index c9136760c67..a68f0f6e4e8 100644 --- a/ddtrace/contrib/internal/logging/patch.py +++ b/ddtrace/contrib/internal/logging/patch.py @@ -5,6 +5,7 @@ import ddtrace from ddtrace import config +from ddtrace._logger import set_log_formatting from ddtrace.contrib.internal.trace_utils import unwrap as _u from ddtrace.internal.constants import LOG_ATTR_ENV from ddtrace.internal.constants import LOG_ATTR_SERVICE @@ -99,6 +100,13 @@ def patch(): _w(logging.Logger, "makeRecord", _w_makeRecord) _w(logging.StrFormatStyle, "_format", _w_StrFormatStyle_format) + if config._logs_injection: + # Only set the formatter is DD_LOGS_INJECTION is set to True. We do not want to modify + # unstructured logs if a user has not enabled logs injection. + # Also, the Datadog log format must be set after the logging module has been patched, + # otherwise the formatter will raise an exception. + set_log_formatting() + def unpatch(): if getattr(logging, "_datadog_patch", False): diff --git a/releasenotes/notes/remove-set-log-formatting-a8b9c7d2e1f3g4h5.yaml b/releasenotes/notes/remove-set-log-formatting-a8b9c7d2e1f3g4h5.yaml deleted file mode 100644 index aad4e62e8c7..00000000000 --- a/releasenotes/notes/remove-set-log-formatting-a8b9c7d2e1f3g4h5.yaml +++ /dev/null @@ -1,5 +0,0 @@ ---- -fixes: - - | - logging: Fixed ddtrace internal logging when trace-log correlation is disabled. - Prevents ``ValueError: Formatting field not found in record: 'dd.service'``. diff --git a/tests/integration/test_integration.py b/tests/integration/test_integration.py index 94a8b95a77b..60aa25db059 100644 --- a/tests/integration/test_integration.py +++ b/tests/integration/test_integration.py @@ -808,8 +808,8 @@ def test_logging_during_tracer_init_succeeds_when_debug_logging_and_logs_injecti assert out == b"", "an empty program should generate no logs under ddtrace-run" assert ( - b"[dd.service=ddtrace_subprocess_dir dd.env= dd.version= dd.trace_id=0 dd.span_id=0]" not in err - ), "stderr should not contain debug output when DD_TRACE_DEBUG is set" + b"[dd.service=ddtrace_subprocess_dir dd.env= dd.version= dd.trace_id=0 dd.span_id=0]" in err + ), "stderr should contain debug output when DD_TRACE_DEBUG is set" assert b"KeyError: 'dd.service'" not in err, "stderr should not contain any exception logs" assert (