Python logging.setLoggerClass() Examples

The following are 30 code examples of logging.setLoggerClass(). 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: test_logger.py    From icloud_photos_downloader with MIT License 6 votes vote down vote up
def test_logger_tqdm_fallback(self):
        logging.setLoggerClass(IPDLogger)
        logger = logging.getLogger("icloudpd-test")
        logger.log = MagicMock()
        logger.set_tqdm_description("foo")
        logger.log.assert_called_once_with(logging.INFO, "foo")

        logger.log = MagicMock()
        logger.tqdm_write("bar")
        logger.log.assert_called_once_with(logging.INFO, "bar")

        logger.set_tqdm(MagicMock())
        logger.tqdm.write = MagicMock()
        logger.tqdm.set_description = MagicMock()
        logger.log = MagicMock()
        logger.set_tqdm_description("baz")
        logger.tqdm.set_description.assert_called_once_with("baz")
        logger.tqdm_write("qux")
        logger.tqdm.write.assert_called_once_with("qux")
        logger.log.assert_not_called 
Example #2
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 #3
Source File: rate_limit.py    From oslo.log with Apache License 2.0 6 votes vote down vote up
def uninstall_filter():
    """Uninstall the rate filter installed by install_filter().

    Do nothing if the filter was already uninstalled.
    """

    if install_filter.log_filter is None:
        # not installed (or already uninstalled)
        return

    # Restore the old logger class
    logging.setLoggerClass(install_filter.logger_class)

    # Remove the filter from all existing loggers
    for logger in _iter_loggers():
        logger.removeFilter(install_filter.log_filter)

    install_filter.logger_class = None
    install_filter.log_filter = None 
Example #4
Source File: scalyr_logging.py    From scalyr-agent-2 with Apache License 2.0 6 votes vote down vote up
def getLogger(name):
    """Returns a logger instance to use for the given name that implements the Scalyr agent's extra logging features.

    This should be used in place of logging.getLogger when trying to retrieve a logging instance that implements
    Scalyr agent's extra features.

    Note, the logger instance will be configured to emit records at INFO level and above.

    @param name: The name of the logger, such as the module name. If this is for a particular monitor instance, then
        the monitor id should be appended at the end surrounded by brackets, such as "my_monitor[1]"

    @return: A logger instance implementing the extra features.
    """
    logging.setLoggerClass(AgentLogger)
    result = logging.getLogger(name)
    result.setLevel(logging.INFO)
    return result


# The single AgentLogManager instance that tracks all of the process wide information necessary to implement
# our logging strategy.  This variable is set to the real variable down below. 
Example #5
Source File: ignis_logging.py    From qiskit-ignis with Apache License 2.0 6 votes vote down vote up
def _initialize(log_config_path):
        """
        Initialize the logging facility for Ignis
        """
        logging.setLoggerClass(IgnisLogger)

        log_config = IgnisLogging._load_config_file(log_config_path)
        # Reading the config file content
        IgnisLogging._file_logging_enabled = \
            log_config.get('file_logging') == "true"
        IgnisLogging._log_file = log_config.get('log_file') if \
            log_config.get('log_file') is not None else "ignis.log"
        max_size = log_config.get('max_size')
        IgnisLogging._max_bytes = int(max_size) if \
            max_size is not None and max_size.isdigit() else 0
        max_rotations = log_config.get('max_rotations')
        IgnisLogging._max_rotations = int(max_rotations) if \
            max_rotations is not None and max_rotations.isdigit() else 0 
Example #6
Source File: logger.py    From icloud_photos_downloader with MIT License 6 votes vote down vote up
def setup_logger(loglevel=DEBUG):
    """Set up logger and add stdout handler"""
    logging.setLoggerClass(IPDLogger)
    logger = logging.getLogger("icloudpd")
    logger.setLevel(loglevel)
    has_stdout_handler = False
    for handler in logger.handlers:
        if handler.name == "stdoutLogger":
            has_stdout_handler = True
    if not has_stdout_handler:
        formatter = logging.Formatter(
            fmt="%(asctime)s %(levelname)-8s %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S")
        stdout_handler = logging.StreamHandler(stream=sys.stdout)
        stdout_handler.setFormatter(formatter)
        stdout_handler.name = "stdoutLogger"
        logger.addHandler(stdout_handler)
    return logger 
Example #7
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 #8
Source File: log.py    From docker-python with Apache License 2.0 6 votes vote down vote up
def _static_init():
        if Log._initialized:
            return

        logging.setLoggerClass(_Logger)
        # The root logger's type is unfortunately (and surprisingly) not affected by
        # `setLoggerClass`. Monkey patch it instead. TODO(vimota): Remove this, see the TODO
        # associated with _Logger.
        logging.RootLogger.findCaller = _Logger.findCaller
        log_to_file = _LOG_TO_FILE_ENV.lower() in ("yes", "true", "t", "1") if _LOG_TO_FILE_ENV is not None else True
        if log_to_file:
            handler = logging.FileHandler(filename='/tmp/kaggle.log', mode='w')
        else:
            handler = logging.StreamHandler()
        
        # ".1s" is for the first letter: http://stackoverflow.com/a/27453084/1869.
        format_string = "%(asctime)s %(levelname).1s %(process)d %(filename)s:%(lineno)d] %(message)s"
        handler.setFormatter(_LogFormatter(format_string))
        logging.basicConfig(level=logging.INFO, handlers=[handler])
        Log._initialized = True 
Example #9
Source File: Base_Logging.py    From qxf2-page-object-model with MIT License 6 votes vote down vote up
def setup_rp_logging(self):
        "Setup reportportal logging"
        try:
            # Setting up a logging.
            logging.setLoggerClass(RPLogger)
            rp_logger = logging.getLogger(__name__)
            rp_logger.setLevel(logging.INFO)
            # Create handler for Report Portal.
            rp_handler = RPLogHandler(pytest.config._config.py_test_service)
            # Set INFO level for Report Portal handler.
            rp_handler.setLevel(logging.INFO)
            return rp_logger
        except Exception as e:
            self.write("Exception when trying to set rplogger")
            self.write(str(e))
            self.exceptions.append("Error when setting up the reportportal logger") 
Example #10
Source File: logger.py    From molecule with MIT License 6 votes vote down vote up
def get_logger(name=None):
    """
    Build a logger with the given name and returns the logger.

    :param name: The name for the logger. This is usually the module
                 name, ``__name__``.
    :return: logger object
    """
    logging.setLoggerClass(CustomLogger)

    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)

    logger.addHandler(_get_info_handler())
    logger.addHandler(_get_out_handler())
    logger.addHandler(_get_warn_handler())
    logger.addHandler(_get_error_handler())
    logger.addHandler(_get_critical_handler())
    logger.addHandler(_get_success_handler())
    logger.propagate = False

    return logger 
Example #11
Source File: log.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def init_logging():
    # type: () -> None
    """
    Initialize logging (set up forwarding to Go backend and sane defaults)
    """
    # Forward to Go backend
    logging.addLevelName(TRACE_LEVEL, 'TRACE')
    logging.setLoggerClass(AgentLogger)
    logging.captureWarnings(True)  # Capture warnings as logs so it's easier for log parsers to handle them.

    rootLogger = logging.getLogger()
    rootLogger.addHandler(AgentLogHandler())
    rootLogger.setLevel(_get_py_loglevel(datadog_agent.get_config('log_level')))

    # `requests` (used in a lot of checks) imports `urllib3`, which logs a bunch of stuff at the info level
    # Therefore, pre emptively increase the default level of that logger to `WARN`
    urllib_logger = logging.getLogger("requests.packages.urllib3")
    urllib_logger.setLevel(logging.WARN)
    urllib_logger.propagate = True 
Example #12
Source File: app.py    From biggraphite with Apache License 2.0 5 votes vote down vote up
def _init_logger(self):
        """Init logger to be able to intercept message from each command."""
        class HandlerWrapper(logging.Handler):
            def emit(self, record):
                # FIXME Configure logging on executor threads
                w = self.bgutil_workers.get(record.threadName, None)
                if not w:
                    return

                w["output"].append(
                    "{:<7} {:<25} :: {}".format(
                        record.levelname,
                        record.filename + ":" + str(record.lineno),
                        record.getMessage(),
                    )
                )

        class LoggerWrapper(logging.Logger):
            def __init__(self, name):
                super(LoggerWrapper, self).__init__(name)
                self.addHandler(HandlerWrapper())
                self.propagate = True

        logging.setLoggerClass(LoggerWrapper)
        logging.getLogger().propagate = True
        logging.getLogger().addHandler(HandlerWrapper()) 
Example #13
Source File: log.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def init_logging():
    logging.addLevelName(TRACE_LEVEL, 'TRACE')
    logging.setLoggerClass(AgentLogger) 
Example #14
Source File: __init__.py    From pyrocore with GNU General Public License v2.0 5 votes vote down vote up
def initialize(cls):
        """ Register test logging.
        """
        logging.addLevelName(TRACE, "TRACE")
        logging.setLoggerClass(cls)

        if any(i in sys.argv for i in ("-v", "--verbose")):
            logging.getLogger().setLevel(TRACE)
        elif any(i in sys.argv for i in ("-q", "--quiet")):
            logging.getLogger().setLevel(logging.INFO) 
Example #15
Source File: __init__.py    From abseil-py with 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 #16
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_manager_loggerclass(self):
        logged = []

        class MyLogger(logging.Logger):
            def _log(self, level, msg, args, exc_info=None, extra=None):
                logged.append(msg)

        man = logging.Manager(None)
        self.assertRaises(TypeError, man.setLoggerClass, int)
        man.setLoggerClass(MyLogger)
        logger = man.getLogger('test')
        logger.warning('should appear in logged')
        logging.warning('should not appear in logged')

        self.assertEqual(logged, ['should appear in logged']) 
Example #17
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 #18
Source File: stenoLogging.py    From legion with GNU General Public License v3.0 5 votes vote down vote up
def get_logger(name, path=None, console=True):
    logging.setLoggerClass(StenoLogger)
    logger = logging.getLogger(name)
    if console == True:
        shdlr = logging.StreamHandler()
        shdlr.setFormatter(StenoFormatter())
        logger.addHandler(shdlr)
    if path:
        fhdlr = RotatingFileHandler(path)
        fhdlr.setFormatter(StenoFormatter())
        logger.addHandler(fhdlr)
    return logger 
Example #19
Source File: log.py    From synthtool with Apache License 2.0 5 votes vote down vote up
def _setup_logging(color: bool = bool(ColoredFormatter)):
    logging.getLogger("urllib3.connectionpool").setLevel(logging.ERROR)
    logging.setLoggerClass(LoggerWithSuccess)

    # Silence any noisy loggers here. 
Example #20
Source File: utils.py    From py-SMART with GNU Lesser General Public License v2.1 5 votes vote down vote up
def configure_trace_logging():
    if getattr(logging.handlers.logging.getLoggerClass(), 'trace', None) is None:
        logging.setLoggerClass(TraceLogger) 
Example #21
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 #22
Source File: oauth2_logger.py    From yahoo_fantasy_api with MIT License 5 votes vote down vote up
def cleanup():
    # Cleanup the logging in yahoo_oauth.  It creates a logger that writes to
    # stderr.  We are going to recreate the logger so that we can use a handler
    # that writes to our log file.
    logging.setLoggerClass(logging.Logger)
    yahoo_oauth.yahoo_oauth.logger = logging.getLogger('mod_yahoo_oauth')
    logging.getLogger('mod_yahoo_oauth').setLevel(logging.WARN) 
Example #23
Source File: __init__.py    From ravestate with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_logger(name: str, logpath: str=None):
    """
    Obtain a file/console logger with a certain name.

    * `name`: The name for the logger. Will appear in all log messages.

    * `logpath`: The path under which a logfile should be created.
     If no path is specified, a default path is used.
     The default path is the working directory if no other path was specified
     by _any_ other reggol client using set_default_logpath(...)!

    **Returns:** A new logger with the given name.
    """
    global _default_logpath
    if not logpath:
        logpath = _default_logpath
    logging.setLoggerClass(CustomConsoleAndFileLogger)
    logger = logging.getLogger(name)
    assert isinstance(logger, CustomConsoleAndFileLogger)
    logger.setLevel(_level)
    logger.set_console_formatter(ColoredFormatter())
    logger.set_file_formatter(file_path=logpath)
    return logger


# Instantiate and configure argparser 
Example #24
Source File: log.py    From popper with MIT License 5 votes vote down vote up
def setup_logging(level="STEP_INFO"):
    """Setups logging facilities with custom Logger and Formatter.

    Args:
      level(str): Level to be logged in custom logger.
                    (Default value = 'STEP_INFO')

    Returns:
      popper.log.PopperLogger: Custom log for that particular level.
    """
    logging.setLoggerClass(PopperLogger)
    log = logging.getLogger("popper")

    formatter = PopperFormatter()

    # INFO/STEP_INFO goes to stdout
    h1 = logging.StreamHandler(sys.stdout)
    h1.addFilter(LevelFilter([logging.INFO, STEP_INFO], False))
    h1.setFormatter(formatter)

    # anything goes to stdout
    h2 = logging.StreamHandler(sys.stderr)
    h2.addFilter(LevelFilter([logging.INFO, STEP_INFO], True))
    h2.setFormatter(formatter)

    log.addHandler(h1)
    log.addHandler(h2)
    log.setLevel(level)

    return log 
Example #25
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 #26
Source File: test_log.py    From opencensus-python with Apache License 2.0 5 votes vote down vote up
def tearDownClass(cls):
        logging.setLoggerClass(cls._old_logger_class) 
Example #27
Source File: trace.py    From opencensus-python with Apache License 2.0 5 votes vote down vote up
def trace_integration(tracer=None):
    """Replace the global default logging class with `TraceLogger`.

    Loggers created after the integration will produce `LogRecord`s
    with extra traceId, spanId, and traceSampled attributes from the opencensus
    context.
    """
    logging.setLoggerClass(TraceLogger) 
Example #28
Source File: test_logging_integration.py    From opencensus-python with Apache License 2.0 5 votes vote down vote up
def tearDownClass(cls):
        logging.setLoggerClass(cls._old_logger_class) 
Example #29
Source File: test_logging.py    From Fluid-Designer 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 #30
Source File: slogging.py    From pyquarkchain with MIT License 5 votes vote down vote up
def getLogger(self, name):
        logging.setLoggerClass(SLogger)
        return super(SManager, self).getLogger(name)