Search code examples
pythongitlab-cisyslog-ng

How to disable syslogger when running tests in GitLab pipeline?


I have defined tests running in GitLab cicd pipeline. I also have syslog-ng set up for logging. The whole app is runnning with docker-compose. I have defined my syslogger like this:

import logging
from logging.handlers import SysLogHandler

def get_logger(name):
    syslog = SysLogHandler(address=("syslog-ng-container", 514))
    logger = logging.getLogger(name)
    logger.setLevel("DEBUG")
    logger.addHandler(syslog)
    return logger

This works perfectly when running the app but when running tests I don't have the syslog-ng-container running and tests fail when trying to import the logger. I was wondering how could I disable setting the syslogger when running tests? I was thinking I could set up some variable e.g.

if TEST is not True:
    syslog = SysLogHandler(address=("syslog-ng-container", 514))
    logger.addHandler(syslog)

Can I set this variable to be True in my .gitlab-ci.yml -file or do I need to specify the TEST = True separately in every test file I have?


Solution

  • When a job runs via GitLab Pipelines, GITLAB_CI is set to true.

    So something like this might be appropriate:

    import os
    
    if os.environ.get("GITLAB_CI")!="true":
        syslog = SysLogHandler(address=("syslog-ng-container", 514))
        logger.addHandler(syslog)
    
    

    If you do not care about the particular value, if "GITLAB_CI" not in os.environ: will also work.

    Although it might not be a bad idea to use a special env. variable for this use case and not depend on "GitLab Pipelines" in particular.