Repository: scoutapp/scout_apm_python (python)

Issue:
Improve debug level logging
We currently don't capture a lot of useful information when logging is set to debug. This can make identifying support issues tough

The configuration that we collect at the top of the log is very useful, but once we get to actually recording the requests, we don't have much visibility. As seen at the bottom of the logs, all we say is when a request starts and ends, and we are missing some valuable information like what time the request started and ended, as well as some of the payload/request information (total duration, maybe complete_spans count?)


For example, here's a script of what debug logs looks like:

```
Defaults : app_server = 
Python   : application_root = /var/www/a
Defaults : collect_remote_ip = True
Null     : core_agent_config_file = None
Defaults : core_agent_dir = /tmp/scout_apm_core
Defaults : core_agent_download = True
Defaults : core_agent_launch = True
Null     : core_agent_log_file = None
Defaults : core_agent_log_level = info
Defaults : core_agent_permissions = 700
Defaults : core_agent_socket_path = tcp://127.0.0.1:6590
Defaults : core_agent_version = v1.3.0
Defaults : disabled_instruments = []
Defaults : download_url = https://s3-us-west-1.amazonaws.com/scout-public-downloads/apm_core_agent/release
Defaults : framework = 
Defaults : framework_version = 
Defaults : hostname = None
Null     : ignore = None
Null     : log_level = None
Python   : monitor = True
Python   : name = asdf
Defaults : revision_sha = 
Defaults : scm_subdirectory = 
Defaults : shutdown_message_enabled = True
Defaults : shutdown_timeout_seconds = 2.0
Instrumenting elasticsearch.
Couldn't import elasticsearch.Elasticsearch - probably not installed.
Instrumenting Jinja2.
Instrumenting pymongo.
Couldn't import pymongo.Collection - probably not installed.
Instrumenting redis.
Instrumenting urllib3.
APM Launching on PID: 40353
Core Agent manifest json: {'version': '1.3.0', 'core_agent_version': '1.3.0', 'core_agent_binary': 'core-agent', 'core_agent_binary_sha256': '51d66d40fe1c3198f82310b21b2023asdfasdfasdfasdfasdfsadfsadfsdaf}
Configuration Loaded:
Defaults : app_server = 
Python   : application_root = /var/www/a
Defaults : collect_remote_ip = True
Null     : core_agent_config_file = None
Defaults : core_agent_dir = /tmp/scout_apm_core
Defaults : core_agent_download = True
Defaults : core_agent_launch = True
Null     : core_agent_log_file = None
Defaults : core_agent_log_level = info
Defaults : core_agent_permissions = 700
Defaults : core_agent_socket_path = tcp://127.0.0.1:6590
Defaults : core_agent_version = v1.3.0
Defaults : disabled_instruments = []
Defaults : download_url = https://s3-us-west-1.amazonaws.com/scout-public-downloads/apm_core_agent/release
Defaults : framework = 
Defaults : framework_version = 
Defaults : hostname = None
Null     : ignore = None
Null     : log_level = None
Python   : monitor = True
Python   : name = a
Defaults : revision_sha = 
Defaults : scm_subdirectory = 
Defaults : shutdown_message_enabled = True
Defaults : shutdown_timeout_seconds = 2.0
Instrumenting elasticsearch.
Couldn't import elasticsearch.Elasticsearch - probably not installed.
Instrumenting Jinja2.
Instrumenting pymongo.
Couldn't import pymongo.Collection - probably not installed.
Instrumenting redis.
Instrumenting urllib3.
APM Launching on PID: 40355
Core Agent manifest json: {'version': '1.3.0', 'core_agent_version': '1.3.0', 'core_agent_binary': 'core-agent', 'core_agent_binary_sha256': '51d66d40fe1c3198f82310b21b202315cfc326207d26ffbasdfasdffdsdf'}
CoreAgentSocketThread attempt 1, connecting to tcp://127.0.0.1:6590, PID: 40354, Thread: <CoreAgentSocketThread(Thread-1, started daemon sdfgsdfg)>
CoreAgentSocketThread connected
Registering with app=a key_prefix=aaa key_format_validated=True host=None
CoreAgentSocketThread attempt 1, connecting to tcp://127.0.0.1:6590, PID: 40353, Thread: <CoreAgentSocketThread(Thread-1, started daemon sdfgsdfg)>
CoreAgentSocketThread connected
Registering with app=a key_prefix=aaa key_format_validated=True host=None
CoreAgentSocketThread attempt 1, connecting to tcp://127.0.0.1:6590, PID: 40355, Thread: <CoreAgentSocketThread(Thread-1, started daemon asdf)>
CoreAgentSocketThread connected
Registering with app=a key_prefix=aaa key_format_validated=True host=None
CoreAgentSocketThread stopping.
CoreAgentSocketThread stopped.
CoreAgentSocketThread stopping.
Installed DB connection created signal handler
CoreAgentSocketThread stopped.
Monkey patched Templates
Installed DB connection created signal handler
Monkey patched Templates
CoreAgentSocketThread stopping.
CoreAgentSocketThread stopped.
Installed DB connection created signal handler
Monkey patched Templates
Starting request: req-81f9727b-15d1-47fb-9ed0-ab7bf1aaaaa
Stopping request: req-81f9727b-15d1-47fb-9ed0-ab7bf1aaaaa
Starting request: req-81f9727b-15d1-47fb-9ed0-ab7bf1aaaaa
Stopping request: req-81f9727b-15d1-47fb-9ed0-ab7bf1aaaaa
Starting request: req-81f9727b-15d1-47fb-9ed0-ab7bf1aaabb
Stopping request: req-81f9727b-15d1-47fb-9ed0-ab7bf1aaabb
Starting request: req-81f9727b-15d1-47fb-9ed0-ab7bf1aaabb
Stopping request: req-81f9727b-15d1-47fb-9ed0-ab7bf1aaabb
Starting request: req-81f9727b-15d1-47fb-9ed0-ab7bf1aaaacc
Stopping request: req-81f9727b-15d1-47fb-9ed0-ab7bf1aaacc
Starting request: req-81f9727b-15d1-47fb-9ed0-ab7bf1aaacc
Stopping request: req-81f9727b-15d1-47fb-9ed0-ab7bf1aaacc
```


Pull request:
Improved debug logging for requests.
It now contains summary information for the request that is
logged after the request has been sent.

Closes #654

Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 84e1880..6eb1893 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,9 @@
 # Changelog
 
 ## Pending
+- Improved debug logging for requests. It now includes some summary
+  information about the request.
+  ([Issue #654](https://github.com/scoutapp/scout_apm_python/issues/654))
 - Added Celery's ``priority`` delivery info to the set of tags.
 - Removed parsing queue time from Amazon ALB header, X-Amzn-Trace-Id.
   The time portion of the header only has the truncated seconds which
diff --git a/src/scout_apm/core/tracked_request.py b/src/scout_apm/core/tracked_request.py
index da79cab..4fe3a00 100644
--- a/src/scout_apm/core/tracked_request.py
+++ b/src/scout_apm/core/tracked_request.py
@@ -149,6 +149,21 @@ class TrackedRequest(object):
                 CoreAgentSocketThread.send(batch_command)
             SamplersThread.ensure_started()
 
+        details = " ".join(
+            "{}={}".format(key, value)
+            for key, value in [
+                ("start_time", self.start_time),
+                ("end_time", self.end_time),
+                ("duration", (self.end_time - self.start_time).total_seconds()),
+                ("active_spans", len(self.active_spans)),
+                ("complete_spans", len(self.complete_spans)),
+                ("tags", len(self.tags)),
+                ("hit_max", self.hit_max),
+                ("is_real_request", self.is_real_request),
+            ]
+        )
+        logger.debug("Request %s %s", self.request_id, details)
+
         from scout_apm.core.context import context
 
         context.clear_tracked_request(self)


Test patch:
diff --git a/tests/unit/core/test_tracked_request.py b/tests/unit/core/test_tracked_request.py
index fcb9062..c3848a2 100644
--- a/tests/unit/core/test_tracked_request.py
+++ b/tests/unit/core/test_tracked_request.py
@@ -185,6 +185,37 @@ def test_finish_does_captures_memory_on_real_requests(tracked_request):
     assert "mem_delta" in tracked_request.tags
 
 
+def test_finish_log_request_info(tracked_request, caplog):
+    tracked_request.start_span(operation="Something")
+    tracked_request.stop_span()
+    tracked_request.is_real_request = True
+    tracked_request.finish()
+
+    assert (
+        "scout_apm.core.tracked_request",
+        logging.DEBUG,
+        "Stopping request: {}".format(tracked_request.request_id),
+    ) in caplog.record_tuples
+
+    assert (
+        "scout_apm.core.tracked_request",
+        logging.DEBUG,
+        (
+            "Request {} ".format(tracked_request.request_id)
+            + "start_time={} ".format(tracked_request.start_time)
+            + "end_time={} ".format(tracked_request.end_time)
+            + "duration={} ".format(
+                (tracked_request.end_time - tracked_request.start_time).total_seconds()
+            )
+            + "active_spans=0 "
+            + "complete_spans=1 "
+            + "tags=1 "
+            + "hit_max=False "
+            + "is_real_request=True"
+        ),
+    ) in caplog.record_tuples
+
+
 def test_is_ignored_default_false(tracked_request):
     assert not tracked_request.is_ignored()