Exemple #1
0
    def test_memhandler_to_logfile_level(self, tmpdir):
        '''When forwarding messages from memory to file, only messages with
        appropriate levels should be passed over'''
        log_path = tmpdir.join('test.log').strpath
        logger.init_prior_config()

        # include random strings in the message for better reliability
        msg1 = 'A debug message Xai(Deihee8a'
        logger.log.debug(msg1)
        msg2 = 'An info message aC2pu}i5chai'
        logger.log.info(msg2)
        msg3 = 'A warn message lai_choow5Ie'
        logger.log.warning(msg3)

        logger.init()
        fh = logger.add_filehandler(filelog_path=log_path, level_file=logging.WARN)
        fh.flush()

        with open(log_path) as log_file:
            lines = log_file.readlines()

        # msg1 nor msg2 should not be there, msg3 should be there
        assert len([line for line in lines if msg1 in line]) == 0
        assert len([line for line in lines if msg2 in line]) == 0
        assert len([line for line in lines if msg3 in line]) == 1
Exemple #2
0
    def test_invalid_level(self, monkeypatch):
        '''Invalid log level in config file should be reverted to default'''
        conf = config.get_config()
        default_level = conf.log_level_stream

        monkeypatch.setattr(conf, 'log_level_stream', 'INVALID')
        logger.init()
        assert logging.getLevelName(logger.stream_handler.level) != 'INVALID'
        assert logging.getLevelName(
            logger.stream_handler.level) == default_level
Exemple #3
0
    def test_logfile_no_write(self, tmpdir):
        '''If file log is not writeable, an exception should be raised'''
        log_file = tmpdir.join('test.log')
        log_path = log_file.strpath
        log_file.write('')
        # make the file inaccessible for writing
        os.chmod(log_path, 0)

        logger.init()
        with pytest.raises(IOError):
            logger.add_filehandler(filelog_path=log_path)
Exemple #4
0
    def test_no_syslog(self):
        '''Syslog should be disabled under testing profile'''
        logger.init()
        root = logging.getLogger()

        msg = ('If this failed, it means we need either set syslog=False'
               'as default in logger.init(), or we need to '
               'introduce new variables in Config to make sure syslog is '
               'disabled during the test suite.')

        if logger.syslog_handler is not None:
            assert logger.syslog_handler not in root.handlers, msg
Exemple #5
0
    def test_logfile(self, tmpdir):
        '''Messages should be logged to file when enabled'''
        log_path = tmpdir.join('test.log').strpath

        logger.init()
        fh = logger.add_filehandler(filelog_path=log_path)
        msg = 'This should appear in the log file'
        logger.log.debug(msg)
        fh.flush()

        with open(log_path) as log_file:
            lines = log_file.readlines()

        assert msg in lines[-1]
Exemple #6
0
def main():
    '''Main entry point executed by runtask script'''
    # Preliminary initialization of logging, so all messages before regular
    # initialization can be logged to stream.
    logger.init_prior_config()

    log.info('Execution started at: %s',
             datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC'))
    log.debug('Using checkb %s', checkb.__version__)

    # parse cmdline
    parser = get_argparser()
    args = parser.parse_args()

    check_args(parser, vars(args))
    log.debug('Parsed arguments: %s', args)
    arg_data = process_args(vars(args))

    # create artifacts directory + subdirs
    try:
        artif_subdir = os.path.join(arg_data['artifactsdir'], 'checkb')
        file_utils.makedirs(artif_subdir)
        log.info("Task artifacts will be saved in: %s",
                 arg_data['artifactsdir'])
    except OSError:
        log.error("Can't create artifacts directory %s", artif_subdir)
        raise

    # initialize logging
    level_stream = logging.DEBUG if args.debug else None
    logger.init(level_stream=level_stream)
    logpath = os.path.join(artif_subdir, 'checkb.log')
    logger.add_filehandler(level_file=logging.DEBUG, filelog_path=logpath)
    logger.remove_mem_handler()

    # start execution
    executor = Executor(arg_data)
    success = executor.execute()

    # finalize
    log.info('Task artifacts were saved in: %s', arg_data['artifactsdir'])
    if config.get_config().profile == config.ProfileName.PRODUCTION:
        log.info('External URL for task artifacts: %s/%s',
                 config.get_config().artifacts_baseurl, arg_data['uuid'])
    log.info('Execution finished at: %s',
             datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC'))
    if not success:
        log.error('Some playbooks failed. Exiting with non-zero exit code.')
    sys.exit(0 if success else 1)
Exemple #7
0
 def test_override_level(self, monkeypatch):
     '''A log level from config file should be correctly applied'''
     conf = config.get_config()
     monkeypatch.setattr(conf, 'log_level_stream', 'CRITICAL')
     logger.init()
     assert logging.getLevelName(logger.stream_handler.level) == 'CRITICAL'