Python logging.setLoggerClass() Examples

The following are code examples for showing how to use logging.setLoggerClass(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: wheel2deb   Author: parkoview   File: logger.py    MIT License 6 votes vote down vote up
def getLogger(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.NOTSET)

    logger.addHandler(_get_debug_handler())
    logger.addHandler(_get_info_handler())
    logger.addHandler(_get_task_handler())
    logger.addHandler(_get_warn_handler())
    logger.addHandler(_get_error_handler())
    logger.addHandler(_get_critical_handler())
    logger.addHandler(_get_summary_handler())
    logger.propagate = False

    return logger 
Example 2
Project: assetQC   Author: david-cattermole   File: logger.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def getLogger(name=BASE_LOG_NAME):
    """
    
    :param name: The logger dot-separated name.
    :type name: str
    :rtype: std_logging.Manager
    :return: Logging object.
    """
    assert isinstance(name, str)
    logConfigPath = config.getLoggingConfigPath()

    # Set the logger class.
    std_logging.setLoggerClass(AssetQCLogger)

    # Configure Logger
    std_logging.addLevelName(LEVEL_PROGRESS, 'PROGRESS')
    std_logging.addLevelName(LEVEL_FAILURE, 'FAILURE')
    std_logging_config.fileConfig(logConfigPath)

    logger = std_logging.getLogger(name)
    assert isinstance(logger, AssetQCLogger)
    return logger 
Example 3
Project: molecule   Author: ansible   File: logger.py    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 4
Project: docker-python   Author: Kaggle   File: log.py    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 5
Project: icloud_photos_downloader   Author: ndbroadbent   File: logger.py    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 6
Project: icloud_photos_downloader   Author: ndbroadbent   File: test_logger.py    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 7
Project: insteon-mqtt   Author: TD22057   File: log.py    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: seqlog   Author: tintoy   File: __init__.py    MIT License 6 votes vote down vote up
def configure_from_dict(config, override_root_logger=True, use_structured_logger=True):
    """
    Configure Seq logging using a dictionary.

    Uses `logging.config.dictConfig()`.

    :param config: A dict containing the configuration.
    :type config: dict
    :param override_root_logger: Override the root logger to use a Seq-specific implementation? (default: True)
    :param use_structured_logger: Configure the default logger class to be StructuredLogger, which support named format arguments? (default: True)
    :type override_root_logger: bool
    """

    if override_root_logger:
        _override_root_logger()

    # Must use StructuredLogger to support named format argments.
    if use_structured_logger:
        logging.setLoggerClass(StructuredLogger)

    logging.config.dictConfig(config) 
Example 9
Project: seqlog   Author: tintoy   File: __init__.py    MIT License 6 votes vote down vote up
def log_to_console(level=logging.WARNING, override_root_logger=False, **kwargs):
    """
    Configure the logging system to send log entries to the console.

    Note that the root logger will not log to Seq by default.

    :param level: The minimum level at which to log.
    :param override_root_logger: Override the root logger, too?
                                 Note - this might cause problems if third-party components try to be clever
                                 when using the logging.XXX functions.
    """

    logging.setLoggerClass(StructuredLogger)

    if override_root_logger:
        _override_root_logger()

    logging.basicConfig(
        style='{',
        handlers=[
            ConsoleStructuredLogHandler()
        ],
        level=level,
        **kwargs
    ) 
Example 10
Project: popper   Author: systemslab   File: log.py    MIT License 6 votes vote down vote up
def setup_logging(level='ACTION_INFO'):
    """
    Setups logging facilities with custom Logger and Formatter
    """
    logging.setLoggerClass(PopperLogger)
    log = logging.getLogger('popper')

    formatter = PopperFormatter()

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

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

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

    return log 
Example 11
Project: openhatch   Author: campbe13   File: patch.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _patch_logger_class():
    """Make sure process name is recorded when loggers are used."""

    try:
        from multiprocessing.process import current_process
    except ImportError:
        current_process = None  # noqa

    logging._acquireLock()
    try:
        OldLoggerClass = logging.getLoggerClass()
        if not getattr(OldLoggerClass, '_process_aware', False):

            class ProcessAwareLogger(OldLoggerClass):
                _process_aware = True

                def makeRecord(self, *args, **kwds):
                    record = OldLoggerClass.makeRecord(self, *args, **kwds)
                    if current_process:
                        record.processName = current_process()._name
                    else:
                        record.processName = ""
                    return record
            logging.setLoggerClass(ProcessAwareLogger)
    finally:
        logging._releaseLock() 
Example 12
Project: NiujiaoDebugger   Author: MrSrc   File: test_logging.py    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 13
Project: NiujiaoDebugger   Author: MrSrc   File: test_logging.py    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 14
Project: pyquarkchain   Author: QuarkChain   File: utils.py    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 15
Project: pyquarkchain   Author: QuarkChain   File: slogging.py    MIT License 5 votes vote down vote up
def getLogger(self, name):
        logging.setLoggerClass(SLogger)
        return super(SManager, self).getLogger(name) 
Example 16
Project: banruo   Author: yingshang   File: log.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def ensure_process_aware_logger(force=False):
    """Make sure process name is recorded when loggers are used."""
    global _process_aware
    if force or not _process_aware:
        logging._acquireLock()
        try:
            _process_aware = True
            Logger = logging.getLoggerClass()
            if getattr(Logger, '_process_aware', False):  # pragma: no cover
                return

            class ProcessAwareLogger(Logger):
                _signal_safe = True
                _process_aware = True

                def makeRecord(self, *args, **kwds):
                    record = Logger.makeRecord(self, *args, **kwds)
                    record.processName = current_process()._name
                    return record

                def log(self, *args, **kwargs):
                    if _in_sighandler:
                        return
                    return Logger.log(self, *args, **kwargs)
            logging.setLoggerClass(ProcessAwareLogger)
        finally:
            logging._releaseLock() 
Example 17
Project: tcex   Author: ThreatConnect-Inc   File: logger.py    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 18
Project: py-helios-node   Author: Helios-Protocol   File: logging.py    MIT License 5 votes vote down vote up
def setup_trace_logging() -> None:
    logging.setLoggerClass(TraceLogger)
    logging.addLevelName(TRACE_LEVEL_NUM, 'TRACE') 
Example 19
Project: py-helios-node   Author: Helios-Protocol   File: logging.py    MIT License 5 votes vote down vote up
def setup_trace_logging() -> None:
    logging.setLoggerClass(TraceLogger)
    logging.addLevelName(TRACE_LEVEL_NUM, 'TRACE')
    setattr(logging, 'TRACE', TRACE_LEVEL_NUM)  # typing: ignore 
Example 20
Project: qatrfm-lib   Author: jlausuch   File: logger.py    GNU General Public License v3.0 5 votes vote down vote up
def getQatrfmLogger(name):
        logging.setLoggerClass(QaTrfmLogger)
        return logging.getLogger(name) 
Example 21
Project: NConf-Workshop-2019   Author: chaindrium-inc   File: logging.py    GNU General Public License v3.0 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 22
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_logging.py    GNU General Public License v2.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 23
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_logging.py    GNU General Public License v2.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 24
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_logging.py    GNU General Public License v2.0 5 votes vote down vote up
def test_subclass_logger_cache(self):
        # bpo-37258
        message = []

        class MyLogger(logging.getLoggerClass()):
            def __init__(self, name='MyLogger', level=logging.NOTSET):
                super().__init__(name, level)
                message.append('initialized')

        logging.setLoggerClass(MyLogger)
        logger = logging.getLogger('just_some_logger')
        self.assertEqual(message, ['initialized'])
        stream = io.StringIO()
        h = logging.StreamHandler(stream)
        logger.addHandler(h)
        try:
            logger.setLevel(logging.DEBUG)
            logger.debug("hello")
            self.assertEqual(stream.getvalue().strip(), "hello")

            stream.truncate(0)
            stream.seek(0)

            logger.setLevel(logging.INFO)
            logger.debug("hello")
            self.assertEqual(stream.getvalue(), "")
        finally:
            logger.removeHandler(h)
            h.close()
            logging.setLoggerClass(logging.Logger) 
Example 25
Project: eyeD3   Author: nicfit   File: log.py    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 26
Project: launch   Author: ros2   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def reset():
    """Reset logging."""
    # Reset existing logging infrastructure
    for logger in LaunchLogger.all_loggers:
        logger.setLevel(logging.NOTSET)
        del logger.handlers[:]
    launch_config.reset()
    logging.setLoggerClass(LaunchLogger)


# Initial module reset 
Example 27
Project: qgis-safecast-plugin   Author: OpenGeoLabs   File: logger.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        logging.setLoggerClass(ColoredLogger) 
Example 28
Project: armada   Author: airshipit   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def setup_chart_deploy_aware_logging():
    logging.setLoggerClass(ChartDeployAwareLogger) 
Example 29
Project: amino   Author: tek   File: logging.py    MIT License 5 votes vote down vote up
def install_logger_class() -> None:
    logging.setLoggerClass(Logger) 
Example 30
Project: blockchain   Author: trustlines-protocol   File: boot.py    MIT License 5 votes vote down vote up
def setup_basic_logging():
    logging.setLoggerClass(CurrentGreenletLogger)
    logging.basicConfig(
        level=os.environ.get("LOGLEVEL", "INFO").upper(),
        format=LOGFORMAT,
        stream=sys.stdout,
    ) 
Example 31
Project: dsbox-ta2   Author: usc-isi-i2   File: mplog.py    MIT License 5 votes vote down vote up
def logged_call(log_queue, func, *args, **kwargs):
    MPLogger.log_queue = log_queue
    logging.setLoggerClass(MPLogger)
    # monkey patch root logger and already defined loggers
    logging.root.__class__ = MPLogger
    for logger in logging.Logger.manager.loggerDict.values():
        if not isinstance(logger, logging.PlaceHolder):
            logger.__class__ = MPLogger
    func(*args, **kwargs) 
Example 32
Project: blockhooks   Author: EthereumWebhooks   File: slogging.py    Apache License 2.0 5 votes vote down vote up
def getLogger(self, name):
        logging.setLoggerClass(SLogger)
        return super(SManager, self).getLogger(name) 
Example 33
Project: byexample   Author: byexamples   File: log.py    GNU General Public License v3.0 5 votes vote down vote up
def init_log_system(level=NOTE, use_colors=False):
    global _logger_stack

    logging.setLoggerClass(XLogger)

    logging.CHAT = CHAT
    logging.addLevelName(CHAT, 'CHAT')

    logging.NOTE = NOTE
    logging.addLevelName(NOTE, 'NOTE')

    logging.TRACE = TRACE
    logging.addLevelName(TRACE, 'TRACE')

    rlog = getLogger(name='byexample')  # root

    ch = XStreamHandler(stream=sys.stdout)

    fmtter = XFormatter('%(message)s')
    ch.setFormatter(fmtter)

    rlog.addHandler(ch)
    rlog.xstream_handler = ch

    # Set up the global logger.
    # Activate and deactivate sub loggers using log_context
    # decorator on the top level functions
    _logger_stack.append(rlog)

    assert level is not None
    assert use_colors is not None
    configure_log_system(default_level=level, use_colors=use_colors)
    rlog.xstream_handler.concerns = None 
Example 34
Project: Peerion   Author: hyperionxtech   File: slogging.py    Apache License 2.0 5 votes vote down vote up
def getLogger(self, name):
        logging.setLoggerClass(SLogger)
        return super(SManager, self).getLogger(name) 
Example 35
Project: xcsvm   Author: albermax   File: log.py    MIT License 5 votes vote down vote up
def _get_logger(self, name):
        old_class = logging.getLoggerClass()
        logging.setLoggerClass(MPILogger.CustomLogger)
        logger = logging.getLogger(name)
        logging.setLoggerClass(old_class)
        return logger

    ###########################################################################
    # Standard logging functions. Log only at mpi rank 0. 
Example 36
Project: vidcutter   Author: ozmartian   File: __main__.py    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 37
Project: netseen   Author: ciscochina   File: logger.py    Apache License 2.0 5 votes vote down vote up
def get_logger(self):
        '''
        get looger
        '''
        logger_name = '%s.%s' % (self.name, 'log')
        logger = logging.getLogger(logger_name)
        if not logger.handlers:
            logger.addHandler(self.get_handler())
        debug = CFG.get('DEBUG')
        if debug:
            logger.setLevel(logging.DEBUG)
        else:
            logger.setLevel(logging.INFO)
        return logger

    # def get_db_logger(self, collection_name="LOG"):
    #     '''
    #     get db logger
    #     '''
    #     logging.setLoggerClass(CustomLogger)
    #     logger_name = '%s.%s'%(self.name, 'db')
    #     logger = logging.getLogger(logger_name)
    #     if not logger.handlers:
    #         db_handler = DBHandler(collection_name)
    #         logger.addHandler(db_handler)
    #     debug = CFG.get('DEBUG')
    #     if debug:
    #         logger.setLevel(logging.DEBUG)
    #     else:
    #         logger.setLevel(logging.INFO)
    #     return logger 
Example 38
Project: openrts   Author: Donkyhotay   File: log.py    GNU General Public License v2.0 5 votes vote down vote up
def setUpLogging(loglevel):
    # Add custom "debug2" level
    logging.setLoggerClass(CustomLogger);
    logging.addLevelName(9, "DEBUG2");
    
    # Create our stream handler
    console = logging.StreamHandler();
    formatter = logging.Formatter('%(name)-4s %(levelname)-8s %(message)s');
    console.setFormatter(formatter);
        
    # Set up all the logging streams
    for logger in ['', 'ai', 'gui', 'reso', 'batt']:
        logging.getLogger(logger).setLevel(loglevel);
        logging.getLogger(logger).addHandler(console);
        logging.getLogger(logger).propagate = False; 
Example 39
Project: sploitkit   Author: dhondta   File: logger.py    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 40
Project: eth-utils   Author: ethereum   File: logging.py    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 41
Project: eth-utils   Author: ethereum   File: test_DEBUG2_logging.py    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 42
Project: KMlogger   Author: kylemede   File: kmLogger.py    GNU General Public License v3.0 5 votes vote down vote up
def setUpLogger(name='generalLoggerName',dr='',lvl=20,addFH=True,addSH=True):
    """ This function is utilized by getLogger to set up a new logging object.
    It will have the default name 'generalLoggerName' and stream handler level
    of 20 unless redefined in the function call.  
    NOTE:
    If a file handler is added, it will have the lowest severity level by 
    default (Currently no need for changing this setting, so it will stay 
    this way for now).  Remember that any messages will be passed up to any 
    parent loggers, so children do not always need their own file handler.
    
    Args:
        name (str): The name for the logging object and 
                    name.log will be the output file written to disk.
        lvl (int): The severity level of messages printed to the screen with 
                    the stream handler, default = 20.
        addFH (boolean): Add a file handler to this logger?  Default severity 
                         level for it will be 1, and it will be named following
                         name+'.log'.  Default = True.
        addSH (boolean): Add a stream handler to this logger? Severity set with 
                        the lvl argument.  Default = True.
    Returns:
        log (KMlogger object): A KMlogger object that was freshly 
                                   instantiated.
    """
    logging.setLoggerClass(KMlogger)
    log = logging.getLogger(name)
    log_dict[name]=log
    log.addNewLvls()
    log.setLevel(1)
    # add the requested handlers to the log
    if addFH:
        log.addFileHandler(dr=dr,lvl=1)
    # make a stream handler
    if addSH:
        log.addStreamHandler(lvl)
    return log    
# END OF FILE 
Example 43
Project: dsrf   Author: ddexnet   File: dsrf_logger.py    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 44
Project: snscrape   Author: JustAnotherArchivist   File: cli.py    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 45
Project: ravestate   Author: Roboy   File: __init__.py    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 46
Project: python-sdk   Author: FISCO-BCOS   File: logging.py    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 47
Project: azurectl   Author: SUSE-Enceladus   File: logger.py    Apache License 2.0 5 votes vote down vote up
def init(level=logging.INFO):
    global log
    logging.setLoggerClass(Logger)
    log = logging.getLogger("azurectl")
    log.setLevel(level) 
Example 48
Project: jumpscale_core8   Author: Jumpscale   File: LoggerFactory.py    Apache License 2.0 5 votes vote down vote up
def _enable_dev_mode(self):
        logging.setLoggerClass(JSLogger)
        self.logging.setLevel(logging.DEBUG)
        self.logging.propagate = False
        logging.lastResort = None
        self.enableConsoleHandler() 
Example 49
Project: pyroscope   Author: pyroscope   File: __init__.py    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 50
Project: pyrocore   Author: pyroscope   File: __init__.py    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 51
Project: abseil-py   Author: abseil   File: __init__.py    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 52
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_logging.py    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 53
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_logging.py    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 54
Project: legion   Author: GoVanguard   File: stenoLogging.py    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 55
Project: cells   Author: AlesTsurko   File: test_logging.py    MIT License 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 56
Project: cells   Author: AlesTsurko   File: test_logging.py    MIT License 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 57
Project: cells   Author: AlesTsurko   File: test_logging.py    MIT License 5 votes vote down vote up
def test_subclass_logger_cache(self):
        # bpo-37258
        message = []

        class MyLogger(logging.getLoggerClass()):
            def __init__(self, name='MyLogger', level=logging.NOTSET):
                super().__init__(name, level)
                message.append('initialized')

        logging.setLoggerClass(MyLogger)
        logger = logging.getLogger('just_some_logger')
        self.assertEqual(message, ['initialized'])
        stream = io.StringIO()
        h = logging.StreamHandler(stream)
        logger.addHandler(h)
        try:
            logger.setLevel(logging.DEBUG)
            logger.debug("hello")
            self.assertEqual(stream.getvalue().strip(), "hello")

            stream.truncate(0)
            stream.seek(0)

            logger.setLevel(logging.INFO)
            logger.debug("hello")
            self.assertEqual(stream.getvalue(), "")
        finally:
            logger.removeHandler(h)
            h.close()
            logging.setLoggerClass(logging.Logger) 
Example 58
Project: py-SMART   Author: freenas   File: utils.py    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 59
Project: actsys   Author: intel-ctrlsys   File: datastore.py    Apache License 2.0 5 votes vote down vote up
def get_logger():
    """
    Return the logger used by the DataStore
    :return:
    """
    logging.setLoggerClass(DataStoreLogger)
    logger = logging.getLogger("Datastore")
    logger.setLevel(DataStore.LOG_LEVEL)
    logger.propagate = False
    return logger 
Example 60
Project: Mediaexplorer   Author: devalls   File: logger.py    GNU General Public License v3.0 5 votes vote down vote up
def init_logger(fname=None, lev=None):
    global logger_object
    global level

    platform_logger = settings.get_setting('platform_log', platformsettings.__file__)
    level = lev or settings.get_setting("debug")

    # Logger propio de plataforma (kodi) se formatea el mensaje y se pasa al modulo de platformlogger
    if platform_logger and not fname and level < 4:
        from platformcode import platformlogger
        logger_object = platformlogger.logger_object

    # Si no está configurado el logger de la plataforma o estamos en nivel 4 (modo reporte)
    # se guarda en mediaexplorer.log, report.log o el que pasemos en fname
    else:
        filename = fname or ('report.log' if level > 3 else 'mediaexplorer.log')
        filetools.makedirs(sysinfo.data_path)

        logging.setLoggerClass(ExtendedLogger)
        handler = Handler(
            os.path.join(sysinfo.data_path, filename),
            mode='a',
            maxBytes=5 * 1024 * 1024,
            backupCount=10,
            encoding=None,
            delay=0
        )

        handler.setFormatter(
            Formatter(
                '%(asctime)12s %(levelname)-5s %(filename)-30s %(funcName)-20s %(lineno)-4s | %(message)s',
                '%H:%M:%S.%f'
            )
        )

        logger_object = logging.getLogger('mediaexplorer')
        logger_object.setLevel(logging.DEBUG)
        logger_object.handlers = [handler]
        logger_object.end_thread = handler.end_thread 
Example 61
Project: config-api   Author: gridengine   File: trace_logger.py    Apache License 2.0 5 votes vote down vote up
def register(cls):
        """ Register custom trace logger with the logging subsystem """

        # Register a new level / name mapping
        logging.addLevelName(TraceLogger.TRACE, TraceLogger.TRACE_NAME)

        # Override the default logging class for the python logger
        logging.setLoggerClass(TraceLogger) 
Example 62
Project: pygears   Author: bogdanvuk   File: log.py    MIT License 4 votes vote down vote up
def register_custom_log(name, level=INFO, cls=CustomLogger):
    '''PyGears integrated logger class.

    Args:
        name: logger name
        verbosity: default logging level:

    CustomLog instances are customizable via :samp:`logger/{logger_name}`
    :ref:`registry <registry:registry>` subtree. The logger instance registry subtree
    contains the following configuration variables:

    - ``level`` (int): All messages that are logged with a verbosity level
      below this configured ``level`` value will be discarded. See
      :ref:`levels` for a list of levels.
    - ``print_traceback`` (bool): If set to ``True``, the traceback will be
      printed along with the log message.

    - optional level name with desired action. Custom actions can be set for
      any verbosity level by passing the function or any already supported
      action to the appropriate registry subtree. Supported actions are:

      - ``exception``: if set, an exception will be raised whenever logging the
        message at the desired level
      - ``debug``: if set, the debugger will be started and execution paused
      - ``pass``: if set, the message will be printed and no further action
        taken; this is usefull for clearing prevously set values

    Sets the verbosity level for the ``core`` logger at ``INFO`` level:

    >>> bind('logger/core/level', INFO)

    Configures the ``typing`` logger to throw exception on warnings:

    >>> bind('logger/typing/warning', 'exception')

    Configures the ``conf`` logger to use custom function on errors:

    >>> bind('logger/conf/errors', custom_func)
    '''
    log_cls = logging.getLoggerClass()
    logging.setLoggerClass(cls)

    reg_name = f'logger/{name}'

    for m in HOOKABLE_LOG_METHODS:
        config.define(f'{reg_name}/{m}', default='pass')

    config.define(f'{reg_name}/level',
                  default=level,
                  setter=partial(set_log_level, name=name))

    config.define(f'{reg_name}/print_traceback', default=True)

    logger = logging.getLogger(name)
    logger.handlers.clear()
    logger.setLevel(level)
    logger.addHandler(logger.get_logger_handler())

    logging.setLoggerClass(log_cls) 
Example 63
Project: PRISM   Author: 1313e   File: _internal.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def getLogger(name=None, filters=None):
    """
    Creates a :obj:`~PRISM_Logger` instance with `name` and adds the provided
    `filters` to it. The returned :obj:`~PRISM_Logger` instance is a child of
    the base :class:`~PRISM_Logger` created with :func:`~set_base_logger`, but
    has its name changed (such that the parent name does not show up in the
    log-file).

    Optional
    --------
    name : str or None. Default: None
        The name of the :obj:`~PRISM_Logger` instance to create.
        If *None*, initialize the base :class:`~PRISM_Logger` instead.
    filters : list of str or None. Default: None
        List of strings naming the filters that must be applied to the created
        :obj:`~PRISM_Logger` instance.
        If *None* or the :obj:`~PRISM_Logger` instance already existed, no
        filters will be applied.

    Returns
    -------
    logger : :obj:`~PRISM_Logger` object
        The created :obj:`~PRISM_Logger` instance.

    """

    # Set Logger name prefix
    prefix = 'prism'

    # Check what the provided name is
    if name is None:
        child_name = prefix
        name = 'PRISM_ROOT'
    else:
        child_name = ".".join([prefix, name])

    # Temporarily set default Logger class to PRISM_Logger and initialize it
    logging.setLoggerClass(PRISM_Logger)
    logger = logging.getLogger(child_name)
    logging.setLoggerClass(logging.Logger)

    # Set name and filters if this logger did not already exist
    if(logger.name != name):
        # Remove prefix from the name of the PRISM_Logger instance
        logger.name = name

        # Set the requested filter(s)
        logger.set_filters(filters)

    # Return it
    return(logger)


# Define custom getLogger function that adds the RFilter 
Example 64
Project: agent-python-pytest   Author: reportportal   File: rp_logging.py    Apache License 2.0 4 votes vote down vote up
def patching_logger_class():
    logger_class = logging.getLoggerClass()
    original_log = logger_class._log
    original_makeRecord = logger_class.makeRecord

    try:
        def wrap_log(original_func):
            @wraps(original_func)
            def _log(self, *args, **kwargs):
                attachment = kwargs.pop('attachment', None)
                if attachment is not None:
                    kwargs.setdefault('extra', {}).update(
                        {'attachment': attachment})
                return original_func(self, *args, **kwargs)
            return _log

        def wrap_makeRecord(original_func):
            @wraps(original_func)
            def makeRecord(self, name, level, fn, lno, msg, args, exc_info,
                           func=None, extra=None, sinfo=None):
                if extra is not None:
                    attachment = extra.pop('attachment', None)
                else:
                    attachment = None
                try:
                    # Python 3.5
                    record = original_func(self, name, level, fn, lno, msg,
                                           args, exc_info, func=func,
                                           extra=extra, sinfo=sinfo)
                except TypeError:
                    # Python 2.7
                    record = original_func(self, name, level, fn, lno, msg,
                                           args, exc_info, func=func,
                                           extra=extra)
                record.attachment = attachment
                return record
            return makeRecord

        if not issubclass(logger_class, RPLogger):
            logger_class._log = wrap_log(logger_class._log)
            logger_class.makeRecord = wrap_makeRecord(logger_class.makeRecord)
            logging.setLoggerClass(RPLogger)
        yield

    finally:
        if not issubclass(logger_class, RPLogger):
            logger_class._log = original_log
            logger_class.makeRecord = original_makeRecord
            logging.setLoggerClass(logger_class) 
Example 65
Project: flask-skeleton   Author: axiaoxin   File: log.py    Apache License 2.0 4 votes vote down vote up
def init_logger(logger_name=settings.LOGGER_NAME,
                logging_level=settings.LOG_LEVEL,
                log_in_console=settings.LOG_IN_CONSOLE,
                log_in_file=settings.LOG_IN_FILE,
                logfile_name=settings.LOGGER_NAME,
                log_path=settings.LOG_PATH,
                split_logfile_by_level=settings.SPLIT_LOGFILE_BY_LEVEL):

    formatter = logging.Formatter(
        '[%(asctime)s] [%(process)d] [%(levelname)s] [%(request_id)s] %(message)s')  # noqa

    if log_in_file:
        if not os.path.exists(log_path):
            os.makedirs(log_path)
        if split_logfile_by_level:
            logging.setLoggerClass(SplitLogger)
            logger = logging.getLogger(logger_name)
            level = logging.getLevelName(logging_level.upper())
            logger.setLevel(level)

            log_files = {
                logging.DEBUG:
                os.path.join(log_path, logfile_name + '.debug.log'),
                logging.INFO:
                os.path.join(log_path, logfile_name + '.info.log'),
                logging.WARNING:
                os.path.join(log_path, logfile_name + '.warning.log'),
                logging.ERROR:
                os.path.join(log_path, logfile_name + '.error.log'),
            }

            for log_level, log_file in log_files.items():
                file_handler = FileHandler(log_file)
                file_handler.setLevel(log_level)
                file_handler.setFormatter(formatter)
                file_handler.addFilter(RequestIDLogFilter())
                logger.addHandler(file_handler)
        else:
            logger = logging.getLogger(logger_name)
            level = logging.getLevelName(logging_level.upper())
            logger.setLevel(level)
            log_file = os.path.join(log_path, logfile_name + '.log')
            file_handler = FileHandler(log_file)
            file_handler.setLevel(logging.DEBUG)
            file_handler.setFormatter(formatter)
            file_handler.addFilter(RequestIDLogFilter())
            logger.addHandler(file_handler)

    if log_in_console:
        logger = logging.getLogger(logger_name)
        level = logging.getLevelName(logging_level.upper())
        logger.setLevel(level)
        console_handler = logging.StreamHandler()
        console_handler.name = "console"
        console_handler.setLevel(logging.DEBUG)
        console_handler.setFormatter(formatter)
        console_handler.addFilter(RequestIDLogFilter())
        logger.addHandler(console_handler)

    return logger 
Example 66
Project: seqlog   Author: tintoy   File: __init__.py    MIT License 4 votes vote down vote up
def log_to_seq(server_url, api_key=None, level=logging.WARNING,
               batch_size=10, auto_flush_timeout=None,
               additional_handlers=None, override_root_logger=False,
               json_encoder_class=None,
               **kwargs):
    """
    Configure the logging system to send log entries to Seq.

    Note that the root logger will not log to Seq by default.

    :param server_url: The Seq server URL.
    :param api_key: The Seq API key (optional).
    :param level: The minimum level at which to log.
    :param batch_size: The number of log entries to collect before publishing to Seq.
    :param auto_flush_timeout: If specified, the time (in seconds) before the current batch is automatically flushed.
    :param additional_handlers: Additional `LogHandler`s (if any).
    :param override_root_logger: Override the root logger, too?
                                 Note - this might cause problems if third-party components try to be clever
                                 when using the logging.XXX functions.
    :json_encoder_class: The custom JSONEncoder class (if any) to use. It not specified, the default JSONEncoder will be used.
    :return: The `SeqLogHandler` that sends events to Seq. Can be used to forcibly flush records to Seq.
    :rtype: SeqLogHandler
    """

    logging.setLoggerClass(StructuredLogger)

    if override_root_logger:
        _override_root_logger()

    log_handlers = [
        SeqLogHandler(server_url, api_key, batch_size, auto_flush_timeout, json_encoder_class)
    ]

    if additional_handlers:
        for additional_handler in additional_handlers:
            log_handlers.append(additional_handler)

    logging.basicConfig(
        style='{',
        handlers=log_handlers,
        level=level,
        **kwargs
    )

    return log_handlers[0]