From 580160b95b6578c94c0018cd89531d1540a19c57 Mon Sep 17 00:00:00 2001
From: Athanasius <github@miggy.org>
Date: Fri, 19 Aug 2022 16:25:30 +0100
Subject: [PATCH] Relay: Add TRACE logging & use in key places

* Define our own TRACE logging level ('deeper' than DEBUG).
* Define `.trace()` method to use it.
* `logger.trace(...)` for duplicate or 'sent to Listeners' messages.

NB: mypy is still unhappy about Logger.trace, despite attempting the same
   workaround asin EDMC.  Hence the `  # type: ignore` on uses.
---
 src/eddn/Relay.py | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/src/eddn/Relay.py b/src/eddn/Relay.py
index bf507bc..06da89f 100644
--- a/src/eddn/Relay.py
+++ b/src/eddn/Relay.py
@@ -10,6 +10,7 @@ import time
 import uuid
 import zlib
 from threading import Thread
+from typing import TYPE_CHECKING
 
 if pathlib.Path(sys.path[0]).as_posix().endswith('/eddn'):
     print(sys.path)
@@ -41,6 +42,23 @@ from zmq import SUB as ZMQ_SUB
 from zmq import SUBSCRIBE as ZMQ_SUBSCRIBE
 
 # Logging has to be configured first before we do anything.
+# Define a TRACE level
+LEVEL_TRACE = 5
+LEVEL_TRACE_ALL = 3
+logging.addLevelName(LEVEL_TRACE, "TRACE")
+logging.addLevelName(LEVEL_TRACE_ALL, "TRACE_ALL")
+logging.TRACE = LEVEL_TRACE  # type: ignore
+logging.TRACE_ALL = LEVEL_TRACE_ALL  # type: ignore
+logging.Logger.trace = lambda self, message, *args, **kwargs: self._log(  # type: ignore
+    logging.TRACE,  # type: ignore
+    message,
+    args,
+    **kwargs
+)
+# isort: off
+if TYPE_CHECKING:
+    from logging import trace, TRACE  # type: ignore # noqa: F401
+# isort: on
 logger = logging.getLogger(__name__)
 logger.setLevel(logging.INFO)
 __logger_channel = logging.StreamHandler()
@@ -168,6 +186,7 @@ class Relay(Thread):
                 if duplicate_messages.is_duplicated(json):
                     # We've already seen this message recently. Discard it.
                     stats_collector.tally("duplicate")
+                    logger.trace('Discarding duplicate message')  # type: ignore
                     return
 
             # Mask the uploader with a randomised nonce but still make it unique
@@ -188,6 +207,7 @@ class Relay(Thread):
             # Send message
             sender.send(message)
             stats_collector.tally("outbound")
+            logger.trace('Sent message to Listeners')  # type: ignore
 
         while True:
             # For each incoming message, spawn a greenlet using the relay_worker