Python logging.setLoggerClass() Examples

The following are 30 code examples for showing how to use logging.setLoggerClass(). 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: icloud_photos_downloader   Author: ndbroadbent   File: test_logger.py    License: MIT License 7 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
Project: qxf2-page-object-model   Author: qxf2   File: Base_Logging.py    License: 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 3
Project: docker-python   Author: Kaggle   File: log.py    License: 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 4
Project: icloud_photos_downloader   Author: ndbroadbent   File: logger.py    License: 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 5
Project: scalyr-agent-2   Author: scalyr   File: scalyr_logging.py    License: 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 6
Project: oslo.log   Author: openstack   File: rate_limit.py    License: 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 7
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 8
Project: qiskit-ignis   Author: Qiskit   File: ignis_logging.py    License: 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 9
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 10
Project: molecule   Author: ansible-community   File: logger.py    License: 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
Project: integrations-core   Author: DataDog   File: log.py    License: 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
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 13
Project: pyquarkchain   Author: QuarkChain   File: slogging.py    License: MIT License 5 votes vote down vote up
def getLogger(self, name):
        logging.setLoggerClass(SLogger)
        return super(SManager, self).getLogger(name) 
Example 14
Project: tcex   Author: ThreatConnect-Inc   File: logger.py    License: Apache License 2.0 5 votes vote down vote up
def _logger(self):
        """Return the logger. The default_args property is not available in init."""
        logging.setLoggerClass(TraceLogger)
        logger = logging.getLogger(self.logger_name)
        logger.setLevel(logging.TRACE)
        return logger 
Example 15
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 16
Project: armada   Author: airshipit   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def setup_chart_deploy_aware_logging():
    logging.setLoggerClass(ChartDeployAwareLogger) 
Example 17
Project: testplan   Author: Morgan-Stanley   File: logger.py    License: Apache License 2.0 5 votes vote down vote up
def _initial_setup():
    """
    Perform initial setup for the logger. Creates and adds a handler to log
    to stdout with default level TEST_INFO.

    :return: root logger object and stdout logging handler
    """
    logging.setLoggerClass(TestplanLogger)
    root_logger = logging.getLogger("testplan")

    # Set the level of the root logger to DEBUG so that nothing is filtered out
    # by the logger itself - the handlers will perform filtering.
    root_logger.setLevel(DEBUG)

    # Set up the stdout log handler. This handler just writes messages out to
    #  stdout without any extra formatting and is intended for user-facing
    # logs. The level is controlled by command-line args so should be set
    # when those args are parsed; however to begin with we set the level to
    # TEST_INFO as a default.
    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_formatter = logging.Formatter("%(message)s")
    stdout_handler.setFormatter(stdout_formatter)
    stdout_handler.setLevel(TEST_INFO)
    root_logger.addHandler(stdout_handler)

    return root_logger, stdout_handler


# Ideally, objects should log by inheriting from "Loggable" and using
# self.logger. However, for classes that don't inherit from Loggable or for
# code outside of a class we provide the root testplan.common.utils.logger
# object here as TESTPLAN_LOGGER. 
Example 18
Project: better-exceptions   Author: Qix-   File: __init__.py    License: MIT License 5 votes vote down vote up
def hook():
    sys.excepthook = excepthook

    logging.setLoggerClass(BetExcLogger)
    patch_logging()

    if hasattr(sys, 'ps1'):
        print('WARNING: better_exceptions will only inspect code from the command line\n'
              '         when using: `python -m better_exceptions\'. Otherwise, only code\n'
              '         loaded from files will be inspected!', file=sys.stderr) 
Example 19
Project: GCA-Matting   Author: Yaoyi-Li   File: logger.py    License: MIT License 5 votes vote down vote up
def get_logger(log_dir=None, tb_log_dir=None, logging_level="DEBUG"):
    """
    Return a default build-in logger if log_file=None and tb_log_dir=None
    Return a build-in logger which dump stdout to log_file if log_file is assigned
    Return a build-in logger and tensorboard summary writer if tb_log_dir is assigned
    :param log_file: logging file dumped from stdout
    :param tb_log_dir: tensorboard dir
    :param logging_level:
    :return: Logger or [Logger, TensorBoardLogger]
    """
    level = LEVELS[logging_level.upper()]
    exp_string = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")

    logging.setLoggerClass(MyLogger)
    logger = logging.getLogger('Logger')
    logger.setLevel(level)
    # create formatter
    formatter = logging.Formatter('[%(asctime)s] %(levelname)s: %(message)s', datefmt='%m-%d %H:%M:%S')

    # create console handler
    ch = logging.StreamHandler()
    ch.setLevel(level)
    ch.setFormatter(formatter)
    # add the handlers to logger
    logger.addHandler(ch)

    # create file handler
    if log_dir is not None and CONFIG.local_rank == 0:
        log_file = os.path.join(log_dir, exp_string)
        fh = logging.FileHandler(log_file+'.log', mode='w')
        fh.setLevel(level)
        fh.setFormatter(formatter)
        logger.addHandler(fh)
        pprint(CONFIG, stream=fh.stream)

    # create tensorboard summary writer
    if tb_log_dir is not None:
        tb_logger = TensorBoardLogger(tb_log_dir=tb_log_dir, exp_string=exp_string)
        return logger, tb_logger
    else:
        return logger 
Example 20
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: 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 21
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 22
Project: vidcutter   Author: ozmartian   File: __main__.py    License: GNU General Public License v3.0 5 votes vote down vote up
def init_logger(self) -> None:
        try:
            log_path = self.get_app_config_path()
        except AttributeError:
            if sys.platform == 'win32':
                log_path = os.path.join(QDir.homePath(), 'AppData', 'Local', qApp.applicationName().lower())
            elif sys.platform == 'darwin':
                log_path = os.path.join(QDir.homePath(), 'Library', 'Preferences', qApp.applicationName().lower())
            else:
                log_path = os.path.join(QDir.homePath(), '.config', qApp.applicationName().lower())
        os.makedirs(log_path, exist_ok=True)
        self.console = ConsoleWidget(self)
        self.consoleLogger = ConsoleHandler(self.console)
        handlers = [logging.handlers.RotatingFileHandler(os.path.join(log_path, '%s.log'
                                                                      % qApp.applicationName().lower()),
                                                         maxBytes=1000000, backupCount=1),
                    self.consoleLogger]
        if self.parser.isSet(self.debug_option) or self.verboseLogs:
            # noinspection PyTypeChecker
            handlers.append(logging.StreamHandler())
        logging.setLoggerClass(VideoLogger)
        logging.basicConfig(handlers=handlers,
                            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                            datefmt='%Y-%m-%d %H:%M',
                            level=logging.INFO)
        logging.captureWarnings(capture=True)
        sys.excepthook = MainWindow.log_uncaught_exceptions
        if os.getenv('DEBUG', False):
            logging.info('appconfig folder: {}'.format(log_path)) 
Example 23
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.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 24
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 25
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 26
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 27
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 28
Project: dsrf   Author: ddexnet   File: dsrf_logger.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, module, log_file_path, fail_fast=False):
    super(DSRFLogger, self).__init__('')
    self.first_error = None
    self._counts = defaultdict(int)
    self.fail_fast = fail_fast
    self.logger = logging.getLogger(module)
    self.log_file_path = log_file_path
    logging.basicConfig(
        filename=log_file_path, filemode='w', level=logging.DEBUG)
    logging.setLoggerClass(DSRFLogger) 
Example 29
Project: snscrape   Author: JustAnotherArchivist   File: cli.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setup_logging():
	logging.setLoggerClass(Logger)
	global logger
	logger = logging.getLogger(__name__) 
Example 30
Project: ravestate   Author: Roboy   File: __init__.py    License: 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