From 21bff86e579a441a64fe06c618e3ef35d33870eb Mon Sep 17 00:00:00 2001
From: Erik Reid <erik.reid@geant.org>
Date: Mon, 31 May 2021 12:30:35 +0200
Subject: [PATCH] init logging

---
 brian_polling_manager/cli.py                  | 10 ++--
 brian_polling_manager/environment.py          | 24 ++++++++
 .../logging_default_config.json               | 59 +++++++++++++++++++
 3 files changed, 89 insertions(+), 4 deletions(-)
 create mode 100644 brian_polling_manager/environment.py
 create mode 100644 brian_polling_manager/logging_default_config.json

diff --git a/brian_polling_manager/cli.py b/brian_polling_manager/cli.py
index 4459299..b5645ea 100644
--- a/brian_polling_manager/cli.py
+++ b/brian_polling_manager/cli.py
@@ -30,7 +30,7 @@ from typing import Union
 import click
 import jsonschema
 
-from brian_polling_manager import inventory, interfaces
+from brian_polling_manager import inventory, interfaces, environment
 
 logger = logging.getLogger(__name__)
 
@@ -59,7 +59,7 @@ _DEFAULT_CONFIG = {
                         '{interface} {ifIndex}'),
         }
     },
-    'statedir': '/tmp/'
+    'statedir': '/tmp/',
 }
 
 CONFIG_SCHEMA = {
@@ -111,7 +111,8 @@ CONFIG_SCHEMA = {
             'minItems': 1
         },
         'sensu': {'$ref': '#/definitions/sensu'},
-        'statedir': {'type': 'string'}
+        'statedir': {'type': 'string'},
+        'logging': {'type': 'string'}
     },
     'required': ['inventory', 'sensu', 'statedir'],
     'additionalProperties': False
@@ -208,6 +209,8 @@ def _validate_config(ctx, param, file):
     except jsonschema.ValidationError as e:
         raise click.BadParameter(str(e))
 
+    environment.setup_logging(config.get('logging', None))
+
     return config
 
 
@@ -237,5 +240,4 @@ def main(config, force):
 
 
 if __name__ == '__main__':
-    logging.basicConfig(level=logging.DEBUG)
     main()
diff --git a/brian_polling_manager/environment.py b/brian_polling_manager/environment.py
new file mode 100644
index 0000000..9662849
--- /dev/null
+++ b/brian_polling_manager/environment.py
@@ -0,0 +1,24 @@
+import json
+import logging.config
+import os
+
+DEFAULT_LOGGING_FILENAME = os.path.join(
+    os.path.dirname(__file__),
+    'logging_default_config.json')
+
+
+def setup_logging(filename=None):
+    """
+    set up logging using the configured filename
+    """
+    if not filename:
+        filename = DEFAULT_LOGGING_FILENAME
+
+    with open(filename) as f:
+        # TODO: this mac workaround should be removed ...
+        d = json.loads(f.read())
+        import platform
+        if platform.system() == 'Darwin':
+            d['handlers']['syslog_handler']['address'] = '/var/run/syslog'
+        logging.config.dictConfig(d)
+        # logging.config.dictConfig(json.loads(f.read()))
diff --git a/brian_polling_manager/logging_default_config.json b/brian_polling_manager/logging_default_config.json
new file mode 100644
index 0000000..bfab907
--- /dev/null
+++ b/brian_polling_manager/logging_default_config.json
@@ -0,0 +1,59 @@
+{
+    "version": 1,
+    "disable_existing_loggers": false,
+    "formatters": {
+        "simple": {
+            "format": "%(asctime)s - %(name)s (%(lineno)d) - %(levelname)s - %(message)s"
+        }
+    },
+
+    "handlers": {
+        "console": {
+            "class": "logging.StreamHandler",
+            "level": "DEBUG",
+            "formatter": "simple",
+            "stream": "ext://sys.stdout"
+        },
+
+        "syslog_handler": {
+            "class": "logging.handlers.SysLogHandler",
+            "level": "DEBUG",
+            "address": "/dev/log",
+            "facility": "user",
+            "formatter": "simple"
+        },
+
+        "info_file_handler": {
+            "class": "logging.handlers.RotatingFileHandler",
+            "level": "INFO",
+            "formatter": "simple",
+            "filename": "info.log",
+            "maxBytes": 10485760,
+            "backupCount": 20,
+            "encoding": "utf8"
+        },
+
+        "error_file_handler": {
+            "class": "logging.handlers.RotatingFileHandler",
+            "level": "ERROR",
+            "formatter": "simple",
+            "filename": "errors.log",
+            "maxBytes": 10485760,
+            "backupCount": 20,
+            "encoding": "utf8"
+        }
+    },
+
+    "loggers": {
+        "brian_polling_manager": {
+            "level": "DEBUG",
+            "handlers": ["console", "syslog_handler"],
+            "propagate": false
+        }
+    },
+
+    "root": {
+        "level": "DEBUG",
+        "handlers": ["console", "syslog_handler"]
+    }
+}
-- 
GitLab