Python logging.getLoggerClass() Examples

The following are 30 code examples of logging.getLoggerClass(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module logging , or try the search function .
Example #1
Source File: log.py    From insteon-mqtt with GNU General Public License v3.0 6 votes vote down vote up
def get_logger(name="insteon_mqtt"):
    """Get a logger object to use.

    This will return a logging object to use for messages.

    Args:
      name (str):  The name of the logging objectd.

    Returns:
      The requested logging object.
    """
    # Force the logging system to use our custom logger class, then restore
    # whatever was set when we're done.
    save = logging.getLoggerClass()
    try:
        logging.setLoggerClass(Logger)
        return logging.getLogger(name)
    finally:
        logging.setLoggerClass(save)


#=========================================================================== 
Example #2
Source File: logger.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _init_log():
    """Initializes the Astropy log--in most circumstances this is called
    automatically when importing astropy.
    """

    global log

    orig_logger_cls = logging.getLoggerClass()
    logging.setLoggerClass(AstropyLogger)
    try:
        log = logging.getLogger('astropy')
        log._set_defaults()
    finally:
        logging.setLoggerClass(orig_logger_cls)

    return log 
Example #3
Source File: logger.py    From pypyr-cli with Apache License 2.0 6 votes vote down vote up
def set_up_notify_log_level():
    """Add up a global notify severity to the python logging package.

    NOTIFY severity is logging level between INFO and WARNING.
    By default it outputs only echo step and step name
    with description.
    """

    # could (should?) be checking hasattr like so:
    # hasattr(logging, levelName):
    # hasattr(logging, methodName):
    # hasattr(logging.getLoggerClass(), methodName):
    # but this extra check is arguably *more* overhead than just assigning it?
    logging.addLevelName(NOTIFY, "NOTIFY")
    logging.NOTIFY = NOTIFY
    logging.getLoggerClass().notify = notify 
Example #4
Source File: __init__.py    From dagster with Apache License 2.0 6 votes vote down vote up
def json_console_logger(init_context):
    level = coerce_valid_log_level(init_context.logger_config['log_level'])
    name = init_context.logger_config['name']

    klass = logging.getLoggerClass()
    logger_ = klass(name, level=level)

    handler = coloredlogs.StandardErrorHandler()

    class JsonFormatter(logging.Formatter):
        def format(self, record):
            return seven.json.dumps(record.__dict__)

    handler.setFormatter(JsonFormatter())
    logger_.addHandler(handler)

    return logger_ 
Example #5
Source File: custom_logger.py    From dagster with Apache License 2.0 6 votes vote down vote up
def json_console_logger(init_context):
    level = init_context.logger_config['log_level']
    name = init_context.logger_config['name']

    klass = logging.getLoggerClass()
    logger_ = klass(name, level=level)

    handler = logging.StreamHandler()

    class JsonFormatter(logging.Formatter):
        def format(self, record):
            return json.dumps(record.__dict__)

    handler.setFormatter(JsonFormatter())
    logger_.addHandler(handler)

    return logger_ 
Example #6
Source File: signal_handlers.py    From st2 with Apache License 2.0 5 votes vote down vote up
def handle_sigusr1(signal_number, stack_frame):
    """
    Global SIGUSR1 signal handler which causes all the loggers to re-open log file handles.

    Note: This function is used with log rotation utilities such as logrotate.
    """
    handlers = logging.getLoggerClass().manager.root.handlers
    reopen_log_files(handlers=handlers) 
Example #7
Source File: log.py    From st2 with Apache License 2.0 5 votes vote down vote up
def setup(config_file, redirect_stderr=True, excludes=None, disable_existing_loggers=False,
          st2_conf_path=None):
    """
    Configure logging from file.

    :param st2_conf_path: Optional path to st2.conf file. If provided and "config_file" path is
                          relative to st2.conf path, the config_file path will get resolved to full
                          absolute path relative to st2.conf.
    :type st2_conf_path: ``str``
    """
    if st2_conf_path and config_file[:2] == './' and not os.path.isfile(config_file):
        # Logging config path is relative to st2.conf, resolve it to full absolute path
        directory = os.path.dirname(st2_conf_path)
        config_file_name = os.path.basename(config_file)
        config_file = os.path.join(directory, config_file_name)

    try:
        logging.config.fileConfig(config_file,
                                  defaults=None,
                                  disable_existing_loggers=disable_existing_loggers)
        handlers = logging.getLoggerClass().manager.root.handlers
        _add_exclusion_filters(handlers=handlers, excludes=excludes)
        if redirect_stderr:
            _redirect_stderr()
    except Exception as exc:
        exc_cls = type(exc)
        tb_msg = traceback.format_exc()

        msg = str(exc)
        msg += '\n\n' + tb_msg

        # revert stderr redirection since there is no logger in place.
        sys.stderr = sys.__stderr__

        # No logger yet therefore write to stderr
        sys.stderr.write('ERROR: %s' % (msg))

        raise exc_cls(six.text_type(msg)) 
Example #8
Source File: logging.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def create_logger(name, debug=False, format=None):
        Logger = getLoggerClass()

        class DebugLogger(Logger):
            def getEffectiveLevel(x):
                if x.level == 0 and debug:
                    return DEBUG
                else:
                    return Logger.getEffectiveLevel(x)

        class DebugHandler(StreamHandler):
            def emit(x, record):
                StreamHandler.emit(x, record) if debug else None

        handler = DebugHandler()
        handler.setLevel(DEBUG)

        if format:
            handler.setFormatter(Formatter(format))

        logger = getLogger(name)
        del logger.handlers[:]
        logger.__class__ = DebugLogger
        logger.addHandler(handler)

        return logger 
Example #9
Source File: test_logging.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_set_logger_class(self):
        self.assertRaises(TypeError, logging.setLoggerClass, object)

        class MyLogger(logging.Logger):
            pass

        logging.setLoggerClass(MyLogger)
        self.assertEqual(logging.getLoggerClass(), MyLogger)

        logging.setLoggerClass(logging.Logger)
        self.assertEqual(logging.getLoggerClass(), logging.Logger) 
Example #10
Source File: logging.py    From cloud-playground with Apache License 2.0 5 votes vote down vote up
def create_logger(app):
    """Creates a logger for the given application.  This logger works
    similar to a regular Python logger but changes the effective logging
    level based on the application's debug flag.  Furthermore this
    function also removes all attached handlers in case there was a
    logger with the log name before.
    """
    Logger = getLoggerClass()

    class DebugLogger(Logger):
        def getEffectiveLevel(x):
            if x.level == 0 and app.debug:
                return DEBUG
            return Logger.getEffectiveLevel(x)

    class DebugHandler(StreamHandler):
        def emit(x, record):
            StreamHandler.emit(x, record) if app.debug else None

    handler = DebugHandler()
    handler.setLevel(DEBUG)
    handler.setFormatter(Formatter(app.debug_log_format))
    logger = getLogger(app.logger_name)
    # just in case that was not a new logger, get rid of all the handlers
    # already attached to it.
    del logger.handlers[:]
    logger.__class__ = DebugLogger
    logger.addHandler(handler)
    return logger 
Example #11
Source File: logging.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def create_logger(app):
    """Creates a logger for the given application.  This logger works
    similar to a regular Python logger but changes the effective logging
    level based on the application's debug flag.  Furthermore this
    function also removes all attached handlers in case there was a
    logger with the log name before.
    """
    Logger = getLoggerClass()

    class DebugLogger(Logger):
        def getEffectiveLevel(x):
            if x.level == 0 and app.debug:
                return DEBUG
            return Logger.getEffectiveLevel(x)

    class DebugHandler(StreamHandler):
        def emit(x, record):
            StreamHandler.emit(x, record) if app.debug else None

    handler = DebugHandler()
    handler.setLevel(DEBUG)
    handler.setFormatter(Formatter(app.debug_log_format))
    logger = getLogger(app.logger_name)
    # just in case that was not a new logger, get rid of all the handlers
    # already attached to it.
    del logger.handlers[:]
    logger.__class__ = DebugLogger
    logger.addHandler(handler)
    return logger 
Example #12
Source File: logging.py    From arithmancer with Apache License 2.0 5 votes vote down vote up
def create_logger(app):
    """Creates a logger for the given application.  This logger works
    similar to a regular Python logger but changes the effective logging
    level based on the application's debug flag.  Furthermore this
    function also removes all attached handlers in case there was a
    logger with the log name before.
    """
    Logger = getLoggerClass()

    class DebugLogger(Logger):
        def getEffectiveLevel(x):
            if x.level == 0 and app.debug:
                return DEBUG
            return Logger.getEffectiveLevel(x)

    class DebugHandler(StreamHandler):
        def emit(x, record):
            StreamHandler.emit(x, record) if app.debug else None

    handler = DebugHandler()
    handler.setLevel(DEBUG)
    handler.setFormatter(Formatter(app.debug_log_format))
    logger = getLogger(app.logger_name)
    # just in case that was not a new logger, get rid of all the handlers
    # already attached to it.
    del logger.handlers[:]
    logger.__class__ = DebugLogger
    logger.addHandler(handler)
    return logger 
Example #13
Source File: logging.py    From appengine-try-python-flask with Apache License 2.0 5 votes vote down vote up
def create_logger(app):
    """Creates a logger for the given application.  This logger works
    similar to a regular Python logger but changes the effective logging
    level based on the application's debug flag.  Furthermore this
    function also removes all attached handlers in case there was a
    logger with the log name before.
    """
    Logger = getLoggerClass()

    class DebugLogger(Logger):
        def getEffectiveLevel(x):
            if x.level == 0 and app.debug:
                return DEBUG
            return Logger.getEffectiveLevel(x)

    class DebugHandler(StreamHandler):
        def emit(x, record):
            StreamHandler.emit(x, record) if app.debug else None

    handler = DebugHandler()
    handler.setLevel(DEBUG)
    handler.setFormatter(Formatter(app.debug_log_format))
    logger = getLogger(app.logger_name)
    # just in case that was not a new logger, get rid of all the handlers
    # already attached to it.
    del logger.handlers[:]
    logger.__class__ = DebugLogger
    logger.addHandler(handler)
    return logger 
Example #14
Source File: test_log.py    From opencensus-python with Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        cls._old_logger_names = get_logger_names()
        cls._old_logger_class = logging.getLoggerClass()
        logging.setLoggerClass(log.TraceLogger) 
Example #15
Source File: test_logging_integration.py    From opencensus-python with Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        cls._old_logger_class = logging.getLoggerClass() 
Example #16
Source File: test_logging_integration.py    From opencensus-python with Apache License 2.0 5 votes vote down vote up
def test_integration(self):
        self.assertEqual(self._old_logger_class, logging.getLoggerClass())
        config_integration.trace_integrations(['logging'])
        self.assertNotEqual(self._old_logger_class, logging.getLoggerClass()) 
Example #17
Source File: logging.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def create_logger(app):
    """Creates a logger for the given application.  This logger works
    similar to a regular Python logger but changes the effective logging
    level based on the application's debug flag.  Furthermore this
    function also removes all attached handlers in case there was a
    logger with the log name before.
    """
    Logger = getLoggerClass()

    class DebugLogger(Logger):
        def getEffectiveLevel(x):
            if x.level == 0 and app.debug:
                return DEBUG
            return Logger.getEffectiveLevel(x)

    class DebugHandler(StreamHandler):
        def emit(x, record):
            StreamHandler.emit(x, record) if app.debug else None

    handler = DebugHandler()
    handler.setLevel(DEBUG)
    handler.setFormatter(Formatter(app.debug_log_format))
    logger = getLogger(app.logger_name)
    # just in case that was not a new logger, get rid of all the handlers
    # already attached to it.
    del logger.handlers[:]
    logger.__class__ = DebugLogger
    logger.addHandler(handler)
    return logger 
Example #18
Source File: logging.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def create_logger(app):
    """Creates a logger for the given application.  This logger works
    similar to a regular Python logger but changes the effective logging
    level based on the application's debug flag.  Furthermore this
    function also removes all attached handlers in case there was a
    logger with the log name before.
    """
    Logger = getLoggerClass()

    class DebugLogger(Logger):
        def getEffectiveLevel(x):
            if x.level == 0 and app.debug:
                return DEBUG
            return Logger.getEffectiveLevel(x)

    class DebugHandler(StreamHandler):
        def emit(x, record):
            StreamHandler.emit(x, record) if app.debug else None

    handler = DebugHandler()
    handler.setLevel(DEBUG)
    handler.setFormatter(Formatter(app.debug_log_format))
    logger = getLogger(app.logger_name)
    # just in case that was not a new logger, get rid of all the handlers
    # already attached to it.
    del logger.handlers[:]
    logger.__class__ = DebugLogger
    logger.addHandler(handler)
    return logger 
Example #19
Source File: logging.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def create_logger(app):
    """Creates a logger for the given application.  This logger works
    similar to a regular Python logger but changes the effective logging
    level based on the application's debug flag.  Furthermore this
    function also removes all attached handlers in case there was a
    logger with the log name before.
    """
    Logger = getLoggerClass()

    class DebugLogger(Logger):
        def getEffectiveLevel(x):
            if x.level == 0 and app.debug:
                return DEBUG
            return Logger.getEffectiveLevel(x)

    class DebugHandler(StreamHandler):
        def emit(x, record):
            StreamHandler.emit(x, record) if app.debug else None

    handler = DebugHandler()
    handler.setLevel(DEBUG)
    handler.setFormatter(Formatter(app.debug_log_format))
    logger = getLogger(app.logger_name)
    # just in case that was not a new logger, get rid of all the handlers
    # already attached to it.
    del logger.handlers[:]
    logger.__class__ = DebugLogger
    logger.addHandler(handler)
    return logger 
Example #20
Source File: logging.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def create_logger(app):
    """Creates a logger for the given application.  This logger works
    similar to a regular Python logger but changes the effective logging
    level based on the application's debug flag.  Furthermore this
    function also removes all attached handlers in case there was a
    logger with the log name before.
    """
    Logger = getLoggerClass()

    class DebugLogger(Logger):
        def getEffectiveLevel(x):
            if x.level == 0 and app.debug:
                return DEBUG
            return Logger.getEffectiveLevel(x)

    class DebugHandler(StreamHandler):
        def emit(x, record):
            StreamHandler.emit(x, record) if app.debug else None

    handler = DebugHandler()
    handler.setLevel(DEBUG)
    handler.setFormatter(Formatter(app.debug_log_format))
    logger = getLogger(app.logger_name)
    # just in case that was not a new logger, get rid of all the handlers
    # already attached to it.
    del logger.handlers[:]
    logger.__class__ = DebugLogger
    logger.addHandler(handler)
    return logger 
Example #21
Source File: logging.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def create_logger(app):
    """Creates a logger for the given application.  This logger works
    similar to a regular Python logger but changes the effective logging
    level based on the application's debug flag.  Furthermore this
    function also removes all attached handlers in case there was a
    logger with the log name before.
    """
    Logger = getLoggerClass()

    class DebugLogger(Logger):
        def getEffectiveLevel(x):
            if x.level == 0 and app.debug:
                return DEBUG
            return Logger.getEffectiveLevel(x)

    class DebugHandler(StreamHandler):
        def emit(x, record):
            StreamHandler.emit(x, record) if app.debug else None

    handler = DebugHandler()
    handler.setLevel(DEBUG)
    handler.setFormatter(Formatter(app.debug_log_format))
    logger = getLogger(app.logger_name)
    # just in case that was not a new logger, get rid of all the handlers
    # already attached to it.
    del logger.handlers[:]
    logger.__class__ = DebugLogger
    logger.addHandler(handler)
    return logger 
Example #22
Source File: tools.py    From irr with Apache License 2.0 5 votes vote down vote up
def addLoggingLevel(level_name, level_num, method_name=None):
    if not method_name:
        method_name = level_name.lower()
    if hasattr(logging, level_name):
        raise AttributeError('{} already defined in logging module'.format(level_name))
    if hasattr(logging, method_name):
        raise AttributeError('{} already defined in logging module'.format(method_name))
    if hasattr(logging.getLoggerClass(), method_name):
        raise AttributeError('{} already defined in logger class'.format(method_name))

    # This method was inspired by the answers to Stack Overflow post
    # http://stackoverflow.com/q/2183233/2988730, especially
    # http://stackoverflow.com/a/13638084/2988730
    def logForLevel(self, message, *args, **kwargs):
        if self.isEnabledFor(level_num):
            self._log(level_num, message, args, **kwargs)

    def logToRoot(message, *args, **kwargs):
        logging.log(level_num, message, *args, **kwargs)

    logging.addLevelName(level_num, level_name)
    setattr(logging, level_name, level_num)
    setattr(logging.getLoggerClass(), method_name, logForLevel)
    setattr(logging, method_name, logToRoot)


# -------------------------------------------------------------------------------------------------
# Looks for sub arguments in the argument structure.
# Retrieve sub arguments for modules such as optimizer_*
# ------------------------------------------------------------------------------------------------- 
Example #23
Source File: test__maaslog.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_doesnt_affect_general_logger_class(self):
        self.patch(logging, "Formatter")
        name = factory.make_string()
        get_maas_logger(name)
        self.assertIsNot(MAASLogger, logging.getLoggerClass()) 
Example #24
Source File: test_clang_indexer.py    From cxxd with GNU General Public License v3.0 5 votes vote down vote up
def test_if_run_on_directory_handles_when_cpp_file_chunk_list_contains_none_items(self):
        import multiprocessing, logging, subprocess
        logging.getLoggerClass().root.handlers[0].baseFilename = 'log_file'
        dummy_cmd = 'cd'
        cpp_file_list = ['/tmp/a.cpp', '/tmp/b.cpp', '/tmp/c.cpp', '/tmp/d.cpp', '/tmp/e.cpp', '/tmp/f.cpp', '/tmp/g.cpp']
        cpp_file_list_chunks = [[cpp_file_list[0], cpp_file_list[1]], [cpp_file_list[2], cpp_file_list[3]], [cpp_file_list[4], cpp_file_list[5]], [cpp_file_list[6], None]]
        with mock.patch.object(self.service, 'symbol_db_exists', return_value=False):
            with mock.patch.object(self.service.symbol_db, 'open') as mock_symbol_db_open:
                with mock.patch.object(self.service.symbol_db, 'create_data_model') as mock_symbol_db_create_data_model:
                    with mock.patch('services.source_code_model.indexer.clang_indexer.get_cpp_file_list', return_value=cpp_file_list) as mock_get_cpp_file_list:
                        with mock.patch('services.source_code_model.indexer.clang_indexer.slice_it', return_value=cpp_file_list_chunks) as mock_slice_it, \
                            mock.patch('services.source_code_model.indexer.clang_indexer.create_indexer_input_list_file', return_value=(None, 'indexer_input_list_file',)) as mock_create_indexer_input_list_file, \
                            mock.patch('services.source_code_model.indexer.clang_indexer.create_empty_symbol_db', return_value=(None, 'empty_symbol_db_filename',)) as mock_create_empty_symbol_db, \
                            mock.patch('services.source_code_model.indexer.clang_indexer.start_indexing_subprocess', return_value=subprocess.Popen(dummy_cmd)) as mock_start_indexing_subprocess, \
                            mock.patch('subprocess.Popen.wait') as mock_subprocess_wait, \
                            mock.patch('services.source_code_model.indexer.clang_indexer.SymbolDatabase.copy_all_entries_from') as mock_symbol_db_copy_all_entries_from, \
                            mock.patch('os.remove') as mock_os_remove:
                            success, args = self.service([SourceCodeModelIndexerRequestId.RUN_ON_DIRECTORY])
        mock_symbol_db_open.assert_called_once_with(self.service.symbol_db_path)
        mock_symbol_db_create_data_model.assert_called_once()
        mock_get_cpp_file_list.assert_called_once_with(self.service.root_directory, self.service.blacklisted_directories, self.service.recognized_file_extensions + self.service.extra_file_extensions)
        mock_slice_it.assert_called_once_with(cpp_file_list, len(cpp_file_list)/multiprocessing.cpu_count())
        mock_create_indexer_input_list_file.assert_called_with(self.service.root_directory, mock.ANY, mock_slice_it.return_value[len(cpp_file_list_chunks)-1])
        mock_create_empty_symbol_db.assert_called_with(self.service.root_directory, self.service.symbol_db_name)
        mock_start_indexing_subprocess.assert_called_with(self.service.root_directory, self.txt_compilation_database.name, mock_create_indexer_input_list_file.return_value[1], mock_create_empty_symbol_db.return_value[1], mock.ANY)
        mock_symbol_db_copy_all_entries_from.assert_called_once()
        self.assertEqual(mock_create_indexer_input_list_file.call_count, len(cpp_file_list_chunks))
        self.assertEqual(mock_create_empty_symbol_db.call_count, len(cpp_file_list_chunks))
        self.assertEqual(mock_start_indexing_subprocess.call_count, len(cpp_file_list_chunks))
        self.assertEqual(mock_os_remove.call_count, 2*len(cpp_file_list_chunks))
        self.assertEqual(mock_subprocess_wait.call_count, len(cpp_file_list_chunks))
        self.assertEqual(success, True)
        self.assertEqual(args, None) 
Example #25
Source File: logger.py    From molecule with MIT License 5 votes vote down vote up
def __init__(self, name, level=logging.NOTSET):
        """Construct CustomLogger."""
        super(logging.getLoggerClass(), self).__init__(name, level)
        logging.addLevelName(SUCCESS, "SUCCESS")
        logging.addLevelName(OUT, "OUT") 
Example #26
Source File: logger.py    From python-sploitkit with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_logger(name, logfile=None, level="INFO"):
    """ Logger initialization function. """
    tmp = logging.getLoggerClass()
    logging.setLoggerClass(SploitkitLogger)
    logger = logging.getLogger(name)
    level = getattr(logging, level)
    logger.setLevel(logging.DEBUG)
    if len(logger.handlers) == 0:
        # setup a StreamHandler for the console (at level INFO)
        ch = ConsoleHandler()
        ch.setFormatter(logging.Formatter(fmt=LOG_FORMAT))
        ch.setLevel(level)
        logger.addHandler(ch)
        if logfile is not None:
            logger.__logfile__ = logfile
            # setup a FileHandler for logging to a file (at level DEBUG)
            fh = RotatingFileHandler(logfile)
            fh.setFormatter(logging.Formatter(LOGFILE_FORMAT,
                                              datefmt=DATETIME_FORMAT))
            fh.setLevel(logging.DEBUG)
            logger.addHandler(fh)
        else:
            logger.__logfile__ = None
    else:
        for h in logger.handlers:
            h.setLevel(level)
    logging.setLoggerClass(tmp)
    return logger 
Example #27
Source File: test_command_meta.py    From python-tackerclient with Apache License 2.0 5 votes vote down vote up
def test_tacker_command_meta_defines_log(self):
        class FakeCommand(tackerV10.TackerCommand):
            pass

        self.assertTrue(helpers.safe_hasattr(FakeCommand, 'log'))
        self.assertIsInstance(FakeCommand.log, logging.getLoggerClass())
        self.assertEqual(FakeCommand.log.name, __name__ + ".FakeCommand") 
Example #28
Source File: logging.py    From Flask with Apache License 2.0 5 votes vote down vote up
def create_logger(app):
    """Creates a logger for the given application.  This logger works
    similar to a regular Python logger but changes the effective logging
    level based on the application's debug flag.  Furthermore this
    function also removes all attached handlers in case there was a
    logger with the log name before.
    """
    Logger = getLoggerClass()

    class DebugLogger(Logger):
        def getEffectiveLevel(x):
            if x.level == 0 and app.debug:
                return DEBUG
            return Logger.getEffectiveLevel(x)

    class DebugHandler(StreamHandler):
        def emit(x, record):
            StreamHandler.emit(x, record) if app.debug else None

    handler = DebugHandler()
    handler.setLevel(DEBUG)
    handler.setFormatter(Formatter(app.debug_log_format))
    logger = getLogger(app.logger_name)
    # just in case that was not a new logger, get rid of all the handlers
    # already attached to it.
    del logger.handlers[:]
    logger.__class__ = DebugLogger
    logger.addHandler(handler)
    return logger 
Example #29
Source File: logging.py    From Flask with Apache License 2.0 5 votes vote down vote up
def create_logger(app):
    """Creates a logger for the given application.  This logger works
    similar to a regular Python logger but changes the effective logging
    level based on the application's debug flag.  Furthermore this
    function also removes all attached handlers in case there was a
    logger with the log name before.
    """
    Logger = getLoggerClass()

    class DebugLogger(Logger):
        def getEffectiveLevel(x):
            if x.level == 0 and app.debug:
                return DEBUG
            return Logger.getEffectiveLevel(x)

    class DebugHandler(StreamHandler):
        def emit(x, record):
            StreamHandler.emit(x, record) if app.debug else None

    handler = DebugHandler()
    handler.setLevel(DEBUG)
    handler.setFormatter(Formatter(app.debug_log_format))
    logger = getLogger(app.logger_name)
    # just in case that was not a new logger, get rid of all the handlers
    # already attached to it.
    del logger.handlers[:]
    logger.__class__ = DebugLogger
    logger.addHandler(handler)
    return logger 
Example #30
Source File: utils.py    From pyquarkchain with MIT License 5 votes vote down vote up
def set_logging_level(cls, level):
        if cls._qkc_logger:
            Logger.warning("logging_level has already been set")
            return
        level_map = {
            "DEBUG": logging.DEBUG,
            "INFO": logging.INFO,
            "WARNING": logging.WARNING,
            "ERROR": logging.ERROR,
            "CRITICAL": logging.CRITICAL,
        }
        level = level.upper()
        if level not in level_map:
            raise RuntimeError("invalid level {}".format(level))

        original_logger_class = logging.getLoggerClass()
        logging.setLoggerClass(QKCLogger)
        cls._qkc_logger = logging.getLogger("qkc")
        logging.setLoggerClass(original_logger_class)

        logging.root.setLevel(level_map[level])

        formatter = QKCLogFormatter()
        handler = logging.StreamHandler()
        handler.setFormatter(formatter)
        logging.root.addHandler(handler)