From 3837cec75e7c09e3ef780ce2b8d868750096c1d5 Mon Sep 17 00:00:00 2001 From: Marcel Pennewiss Date: Thu, 31 Oct 2019 20:21:12 +0100 Subject: [PATCH] Add cron option to suppress logging to stdout --- README.md | 3 ++- config.json | 1 + gitlab-ldap-sync.py | 21 +++++++++++++++++---- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 4ec66f3..19565e4 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ How to configure config.json { "log": "/tmp/gitlab-ldap-sync.log", // Where to store the log file. If not set, will log to stdout "log_level": "INFO", // The log level + "cron": false, // Should the script run as cronjob suppressing any output to stdout "gitlab": { "api": "https://gitlab.example.com", // Url of your GitLab "private_token": "xxxxxxxxxxxxxxxxxxxx", // Token generated in GitLab for an user with admin access @@ -129,4 +130,4 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file ## Acknowledgments -* Hat tip to anyone whose code was used \ No newline at end of file +* Hat tip to anyone whose code was used diff --git a/config.json b/config.json index 503c4c5..f45eabf 100644 --- a/config.json +++ b/config.json @@ -1,6 +1,7 @@ { "log": "/tmp/gitlab-ldap-sync.log", "log_level": "INFO", + "cron": false, "gitlab": { "api": "", "private_token": "", diff --git a/gitlab-ldap-sync.py b/gitlab-ldap-sync.py index a2c3de7..c00b71e 100755 --- a/gitlab-ldap-sync.py +++ b/gitlab-ldap-sync.py @@ -8,14 +8,23 @@ import ldap.asyncsearch import logging +CRON = False + +def logstdout(s): + if not CRON: + print(s) + if __name__ == "__main__": - print('Initializing gitlab-ldap-sync.') config = None with open('config.json') as f: config = json.load(f) + if config is None: + logstdout('Initializing gitlab-ldap-sync failed.') if config is not None: - print('Done.') - print('Updating logger configuration') + logstdout('Initializing gitlab-ldap-sync successfull.') + if config['cron']: + CRON = True + logstdout('Updating logger configuration') log_option = { 'format': '[%(asctime)s] [%(levelname)s] %(message)s' } @@ -24,7 +33,11 @@ if config['log_level']: log_option['level'] = getattr(logging, str(config['log_level']).upper()) logging.basicConfig(**log_option) - print('Done.') + if config['cron'] and config['log']: + console = logging.StreamHandler() + console.setLevel(logging.ERROR) + logging.getLogger('').addHandler(console) + logstdout('Done.') logging.info('Connecting to GitLab') if config['gitlab']['api']: gl = None