Python logging.getLoggerClass() Examples

The following are 30 code examples for showing how to use logging.getLoggerClass(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module logging , or try the search function .

Example 1
Project: dagster   Author: dagster-io   File: custom_logger.py    License: 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 2
Project: dagster   Author: dagster-io   File: __init__.py    License: 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 3
Project: insteon-mqtt   Author: TD22057   File: log.py    License: 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 4
Project: pypyr-cli   Author: pypyr   File: logger.py    License: 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 5
Project: Carnets   Author: holzschu   File: logger.py    License: 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 6
Project: pyquarkchain   Author: QuarkChain   File: utils.py    License: 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) 
Example 7
Project: eyeD3   Author: nicfit   File: log.py    License: GNU General Public License v3.0 5 votes vote down vote up
def getLogger(name):
    og_class = logging.getLoggerClass()
    try:
        logging.setLoggerClass(Logger)
        return logging.getLogger(name)
    finally:
        logging.setLoggerClass(og_class)


# The main 'eyed3' logger 
Example 8
Project: py-kms   Author: SystemRage   File: pykms_Misc.py    License: The Unlicense 5 votes vote down vote up
def add_logging_level(levelName, levelNum, methodName = None):
        """ Adds a new logging level to the `logging` module and the currently configured logging class.
        `levelName` becomes an attribute of the `logging` module with the value `levelNum`.
        `methodName` becomes a convenience method for both `logging` itself and the class returned by `logging.getLoggerClass()`
        (usually just `logging.Logger`). If `methodName` is not specified, `levelName.lower()` is used.

        To avoid accidental clobberings of existing attributes, this method will raise an `AttributeError` if the level name
        is already an attribute of the `logging` module or if the method name is already present .

        Example
        -------
        >>> add_logging_level('TRACE', logging.DEBUG - 5)
        >>> logging.getLogger(__name__).setLevel("TRACE")
        >>> logging.getLogger(__name__).trace('that worked')
        >>> logging.trace('so did this')
        >>> logging.TRACE
        5
        """

        if not methodName:
                methodName = levelName.lower()

        if hasattr(logging, levelName) or hasattr(logging, methodName) or hasattr(logging.getLoggerClass(), methodName):
                return

        def logForLevel(self, message, *args, **kwargs):
                if self.isEnabledFor(levelNum):
                        self._log(levelNum, message, args, **kwargs)
        def logToRoot(message, *args, **kwargs):
                logging.log(levelNum, message, *args, **kwargs)

        logging.addLevelName(levelNum, levelName)
        setattr(logging, levelName, levelNum)
        setattr(logging.getLoggerClass(), methodName, logForLevel)
        setattr(logging, methodName, logToRoot) 
Example 9
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: 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
Project: vidcutter   Author: ozmartian   File: videocutter.py    License: GNU General Public License v3.0 5 votes vote down vote up
def viewLogs() -> None:
        QDesktopServices.openUrl(QUrl.fromLocalFile(logging.getLoggerClass().root.handlers[0].baseFilename)) 
Example 11
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.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 12
Project: dagster   Author: dagster-io   File: test_logging.py    License: Apache License 2.0 5 votes vote down vote up
def test_file_logger(init_context):
    klass = logging.getLoggerClass()
    logger_ = klass(
        init_context.logger_config['name'], level=init_context.logger_config['log_level']
    )
    handler = LogTestFileHandler(init_context.logger_config['file_path'])
    logger_.addHandler(handler)
    handler.setLevel(init_context.logger_config['log_level'])
    return logger_ 
Example 13
Project: dagster   Author: dagster-io   File: log.py    License: Apache License 2.0 5 votes vote down vote up
def construct_single_handler_logger(name, level, handler):
    check.str_param(name, 'name')
    check.inst_param(handler, 'handler', logging.Handler)

    level = coerce_valid_log_level(level)

    @logger
    def single_handler_logger(_init_context):
        klass = logging.getLoggerClass()
        logger_ = klass(name, level=level)
        logger_.addHandler(handler)
        handler.setLevel(level)
        return logger_

    return single_handler_logger 
Example 14
Project: Flask-P2P   Author: chalasr   File: logging.py    License: MIT License 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 15
Project: oslo.log   Author: openstack   File: rate_limit.py    License: Apache License 2.0 5 votes vote down vote up
def install_filter(burst, interval, except_level='CRITICAL'):
    """Install a rate limit filter on existing and future loggers.

    Limit logs to *burst* messages every *interval* seconds, except of levels
    >= *except_level*. *except_level* is a log level name like 'CRITICAL'. If
    *except_level* is an empty string, all levels are filtered.

    The filter uses a monotonic clock, the timestamp of log records is not
    used.

    Raise an exception if a rate limit filter is already installed.
    """

    if install_filter.log_filter is not None:
        raise RuntimeError("rate limit filter already installed")

    try:
        except_levelno = _LOG_LEVELS[except_level]
    except KeyError:
        raise ValueError("invalid log level name: %r" % except_level)

    log_filter = _LogRateLimit(burst, interval, except_levelno)

    install_filter.log_filter = log_filter
    install_filter.logger_class = logging.getLoggerClass()

    class RateLimitLogger(install_filter.logger_class):
        def __init__(self, *args, **kw):
            logging.Logger.__init__(self, *args, **kw)
            self.addFilter(log_filter)

    # Setup our own logger class to automatically add the filter
    # to new loggers.
    logging.setLoggerClass(RateLimitLogger)

    # Add the filter to all existing loggers
    for logger in _iter_loggers():
        logger.addFilter(log_filter) 
Example 16
Project: eth-utils   Author: ethereum   File: logging.py    License: MIT License 5 votes vote down vote up
def _use_logger_class(logger_class: Type[logging.Logger]) -> Iterator[None]:
    original_logger_class = logging.getLoggerClass()
    logging.setLoggerClass(logger_class)
    try:
        yield
    finally:
        logging.setLoggerClass(original_logger_class) 
Example 17
Project: eth-utils   Author: ethereum   File: test_get_logger.py    License: MIT License 5 votes vote down vote up
def test_get_logger_preserves_logging_module_config():
    assert logging.getLoggerClass() is logging.Logger

    path = "testing.{0}".format(uuid.uuid4())
    logger = get_logger(path, CustomLogger)
    assert isinstance(logger, CustomLogger)

    assert logging.getLoggerClass() is logging.Logger 
Example 18
Project: eth-utils   Author: ethereum   File: test_DEBUG2_logging.py    License: MIT License 5 votes vote down vote up
def DEBUG2_installed():
    # caplog only works on loggers retrieved from `logging.getLogger` so we
    # have to use that mechanism to instantiate our logger.
    original_logger = logging.getLoggerClass()
    logging.setLoggerClass(ExtendedDebugLogger)

    try:
        yield
    finally:
        logging.setLoggerClass(original_logger) 
Example 19
Project: python-sdk   Author: FISCO-BCOS   File: logging.py    License: MIT License 5 votes vote down vote up
def _use_logger_class(logger_cls: Type[logging.Logger]) -> Iterator:
    original_logger_cls = logging.getLoggerClass()
    logging.setLoggerClass(logger_cls)
    try:
        yield
    finally:
        logging.setLoggerClass(original_logger_cls) 
Example 20
Project: abseil-py   Author: abseil   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def _initialize():
  """Initializes loggers and handlers."""
  global _absl_logger, _absl_handler

  if _absl_logger:
    return

  original_logger_class = logging.getLoggerClass()
  logging.setLoggerClass(ABSLLogger)
  _absl_logger = logging.getLogger('absl')
  logging.setLoggerClass(original_logger_class)

  python_logging_formatter = PythonFormatter()
  _absl_handler = ABSLHandler(python_logging_formatter) 
Example 21
Project: st2   Author: StackStorm   File: log.py    License: 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 22
Project: st2   Author: StackStorm   File: signal_handlers.py    License: 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 23
Project: PhonePi_SampleServer   Author: priyankark   File: logging.py    License: 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 24
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 25
Project: cloud-playground   Author: googlearchive   File: logging.py    License: 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 26
Project: syntheticmass   Author: synthetichealth   File: logging.py    License: 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 27
Project: arithmancer   Author: google   File: logging.py    License: 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 28
Project: appengine-try-python-flask   Author: googlearchive   File: logging.py    License: 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
Project: opencensus-python   Author: census-instrumentation   File: test_log.py    License: 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 30
Project: opencensus-python   Author: census-instrumentation   File: test_logging_integration.py    License: Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        cls._old_logger_class = logging.getLoggerClass()