From 12b7195dcdda3ce1aa0f8abb9eb6359254f86da1 Mon Sep 17 00:00:00 2001
From: Jan David Mol <mol@astron.nl>
Date: Wed, 31 Mar 2021 18:49:54 +0200
Subject: [PATCH] Add example log rerouting to Kibana (and Python) to SDP
 device

---
 SDP/SDP/SDP.py           | 12 +++++++++++-
 SDP/SDP/lofar_logging.py | 29 +++++++++++++++++++++++++++++
 2 files changed, 40 insertions(+), 1 deletion(-)
 create mode 100644 SDP/SDP/lofar_logging.py

diff --git a/SDP/SDP/SDP.py b/SDP/SDP/SDP.py
index ee98bab36..df14607f1 100644
--- a/SDP/SDP/SDP.py
+++ b/SDP/SDP/SDP.py
@@ -26,10 +26,11 @@ import numpy
 
 from wrappers import only_in_states, only_when_on, fault_on_error
 from opcua_connection import OPCUAConnection
+from lofar_logging import PythonLoggingMixin
 
 __all__ = ["SDP", "main"]
 
-class SDP(Device):
+class SDP(Device, PythonLoggingMixin):
     """
 
     **Properties:**
@@ -485,4 +486,13 @@ def main(args=None, **kwargs):
 
 
 if __name__ == '__main__':
+    x = Device.error_stream
+
+    def new_error_stream(self, *args, **kwargs):
+        print("logging to python")
+        logger.error(*args, **kwargs)
+        print("logging to tango")
+        x.error_stream(self, *args, **kwargs)
+    Device.error_stream = new_error_stream
+
     main()
diff --git a/SDP/SDP/lofar_logging.py b/SDP/SDP/lofar_logging.py
new file mode 100644
index 000000000..09b8e5268
--- /dev/null
+++ b/SDP/SDP/lofar_logging.py
@@ -0,0 +1,29 @@
+import logging
+
+def configured_logger(name=''):
+    logger = logging.getLogger(name)
+    logger.setLevel(logging.DEBUG)
+
+    try:
+        from logstash_async.handler import AsynchronousLogstashHandler
+
+        logger.addHandler(AsynchronousLogstashHandler("elk", 5959, database_path='logstash_test.db'))
+    except Exception:
+        logger.exception("Cannot import or configure logstash_async module, not forwarding logs to ELK stack.")
+
+    return logger
+
+logger = configured_logger()
+
+class PythonLoggingMixin(object):
+    """ Also inherit this class to have your Tango Device log to python instead. """
+
+    # Monkey patch the python logger to replace the tango logger
+    debug_stream = logger.debug
+    info_stream = logger.info
+    warn_stream = logger.warning
+    warning_stream = logger.warning
+    error_stream = logger.error
+    fatal_stream = logger.fatal
+    critical_stream = logger.critical
+
-- 
GitLab