Python logging.Logger() Examples

The following are 30 code examples for showing how to use logging.Logger(). 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: query-exporter   Author: albertodonato   File: config.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _warn_if_unused(config: Config, logger: Logger):
    """Warn if there are unused databases or metrics defined."""
    used_dbs: Set[str] = set()
    used_metrics: Set[str] = set()
    for query in config.queries.values():
        used_dbs.update(query.databases)
        used_metrics.update(metric.name for metric in query.metrics)

    unused_dbs = sorted(set(config.databases) - used_dbs)
    if unused_dbs:
        logger.warning(
            f"unused entries in \"databases\" section: {', '.join(unused_dbs)}"
        )
    unused_metrics = sorted(set(config.metrics) - GLOBAL_METRICS - used_metrics)
    if unused_metrics:
        logger.warning(
            f"unused entries in \"metrics\" section: {', '.join(unused_metrics)}"
        ) 
Example 2
Project: codepost-python   Author: codepost-io   File: custom_logging.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_logger(name=None):
    # type: (str) -> _logging.Logger
    """
    Return a logger with the specified name, creating it if necessary.

    If no name is specified, return the root logger.
    """
    global _logger

    if name == None or name == "":

        # Configure it the first time
        if _logger == None:
            _logger = _setup_logging(LOG_DEFAULT_SCOPE)

        return _logger
    else:
        return _setup_logging(name)

# ============================================================================= 
Example 3
Project: jsonrpcclient   Author: bcb   File: log.py    License: MIT License 6 votes vote down vote up
def log_(
    message: str,
    logger: logging.Logger,
    level: str = "info",
    extra: Optional[Dict] = None,
    trim: bool = False,
) -> None:
    """
    Log a request or response

    Args:
        message: JSON-RPC request or response string.
        level: Log level.
        extra: More details to include in the log entry.
        trim: Abbreviate log messages.
    """
    if extra is None:
        extra = {}
    # Clean up the message for logging
    if message:
        message = message.replace("\n", "").replace("  ", " ").replace("{ ", "{")
    if trim:
        message = _trim_message(message)
    # Log.
    getattr(logger, level)(message, extra=extra) 
Example 4
Project: calmjs   Author: calmjs   File: utils.py    License: GNU General Public License v2.0 6 votes vote down vote up
def enable_pretty_logging(logger='calmjs', level=logging.DEBUG, stream=None):
    """
    Shorthand to enable pretty logging
    """

    def cleanup():
        logger.removeHandler(handler)
        logger.level = old_level

    if not isinstance(logger, logging.Logger):
        logger = logging.getLogger(logger)

    old_level = logger.level
    handler = logging.StreamHandler(stream)
    handler.setFormatter(logging.Formatter(
        u'%(asctime)s %(levelname)s %(name)s %(message)s'))
    logger.addHandler(handler)
    logger.setLevel(level)
    return cleanup 
Example 5
Project: botbuilder-python   Author: microsoft   File: skill_http_client.py    License: MIT License 6 votes vote down vote up
def __init__(
        self,
        credential_provider: SimpleCredentialProvider,
        skill_conversation_id_factory: ConversationIdFactoryBase,
        channel_provider: ChannelProvider = None,
        logger: Logger = None,
    ):
        if not skill_conversation_id_factory:
            raise TypeError(
                "SkillHttpClient(): skill_conversation_id_factory can't be None"
            )

        super().__init__(credential_provider)

        self._skill_conversation_id_factory = skill_conversation_id_factory
        self._channel_provider = channel_provider 
Example 6
Project: glazier   Author: google   File: log_copy.py    License: Apache License 2.0 6 votes vote down vote up
def _EventLogUpload(self, source_log: Text):
    """Upload the log file contents to the local EventLog."""
    event_handler = logging.handlers.NTEventLogHandler('GlazierBuildLog')
    logger = logging.Logger('eventlogger')
    logger.addHandler(event_handler)
    logger.setLevel(logging.DEBUG)

    try:
      with open(source_log, 'r') as f:
        content = f.readlines()
        for line in content:
          logger.info(line)
    except IOError:
      raise LogCopyError(
          'Unable to open log file. It will not be imported into '
          'the Windows Event Log.') 
Example 7
Project: stoq   Author: PUNCH-Cyber   File: plugin_manager.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(
        self,
        plugin_dir_list: List[str],
        plugin_opts: Optional[Dict[str, Dict]] = None,
        stoq_config: Optional[helpers.StoqConfigParser] = None,
    ) -> None:
        self._stoq_config = stoq_config
        self._plugin_opts = {} if plugin_opts is None else plugin_opts
        self._plugin_name_to_info: Dict[str, Tuple[str, helpers.StoqConfigParser]] = {}
        self._loaded_plugins: Dict[str, BasePlugin] = {}
        self._loaded_provider_plugins: Dict[str, ProviderPlugin] = {}
        self._loaded_worker_plugins: Dict[str, WorkerPlugin] = {}
        self._loaded_source_archiver_plugins: Dict[str, ArchiverPlugin] = {}
        self._loaded_dest_archiver_plugins: Dict[str, ArchiverPlugin] = {}
        self._loaded_dispatcher_plugins: Dict[str, DispatcherPlugin] = {}
        self._loaded_connector_plugins: List[ConnectorPlugin] = []
        self._loaded_decorator_plugins: Dict[str, DecoratorPlugin] = {}

        if not hasattr(self, 'log') or self.log is None:
            self.log: logging.Logger = logging.getLogger('stoq')
        self._collect_plugins(plugin_dir_list) 
Example 8
Project: misp42splunk   Author: remg427   File: log.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def log_enter_exit(logger):
    '''Decorator for logger to log function enter and exit.

    This decorator will generate a lot of debug log, please add this
    only when it is required.

    :param logger: Logger to decorate.
    :type logger: ``logging.Logger``

    Usage::
      >>> @log_enter_exit
      >>> def myfunc():
      >>>     doSomething()
    '''

    def log_decorator(func):
        def wrapper(*args, **kwargs):
            logger.debug('%s entered', func.__name__)
            result = func(*args, **kwargs)
            logger.debug('%s exited', func.__name__)
            return result

        return wrapper

    return log_decorator 
Example 9
Project: misp42splunk   Author: remg427   File: log.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def log_enter_exit(logger):
    '''Decorator for logger to log function enter and exit.

    This decorator will generate a lot of debug log, please add this
    only when it is required.

    :param logger: Logger to decorate.
    :type logger: ``logging.Logger``

    Usage::
      >>> @log_enter_exit
      >>> def myfunc():
      >>>     doSomething()
    '''

    def log_decorator(func):
        def wrapper(*args, **kwargs):
            logger.debug('%s entered', func.__name__)
            result = func(*args, **kwargs)
            logger.debug('%s exited', func.__name__)
            return result

        return wrapper

    return log_decorator 
Example 10
Project: tornado-zh   Author: tao12345666333   File: log_test.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        self.formatter = LogFormatter(color=False)
        # Fake color support.  We can't guarantee anything about the $TERM
        # variable when the tests are run, so just patch in some values
        # for testing.  (testing with color off fails to expose some potential
        # encoding issues from the control characters)
        self.formatter._colors = {
            logging.ERROR: u("\u0001"),
        }
        self.formatter._normal = u("\u0002")
        # construct a Logger directly to bypass getLogger's caching
        self.logger = logging.Logger('LogFormatterTest')
        self.logger.propagate = False
        self.tempdir = tempfile.mkdtemp()
        self.filename = os.path.join(self.tempdir, 'log.out')
        self.handler = self.make_handler(self.filename)
        self.handler.setFormatter(self.formatter)
        self.logger.addHandler(self.handler) 
Example 11
Project: tornado-zh   Author: tao12345666333   File: log_test.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        self.formatter = LogFormatter(color=False)
        # Fake color support.  We can't guarantee anything about the $TERM
        # variable when the tests are run, so just patch in some values
        # for testing.  (testing with color off fails to expose some potential
        # encoding issues from the control characters)
        self.formatter._colors = {
            logging.ERROR: u("\u0001"),
        }
        self.formatter._normal = u("\u0002")
        # construct a Logger directly to bypass getLogger's caching
        self.logger = logging.Logger('LogFormatterTest')
        self.logger.propagate = False
        self.tempdir = tempfile.mkdtemp()
        self.filename = os.path.join(self.tempdir, 'log.out')
        self.handler = self.make_handler(self.filename)
        self.handler.setFormatter(self.formatter)
        self.logger.addHandler(self.handler) 
Example 12
Project: llvm-zorg   Author: llvm   File: test_logger.py    License: Apache License 2.0 6 votes vote down vote up
def test_logger(self):  # type: () -> ()
        # This test assumes the initial, intended semantics of the various
        # loggers returned. If semantics change, so must the tests.
        init_level = L._root.level
        test_level = 7
        log_name = "TestLoggerLogger"
        log = L.get_logger(log_name)

        with self.subTest(method=L.get_logger):
            self.assertEqual(log.__class__, logging.Logger)
            self.assertEqual(log_name, log.name)
            # Returned loggers should default to 0 (inherit parent level)
            self.assertEqual(0, log.level)

        with self.subTest(method=L.set_level):
            # Assert set_level() sets root level, not sublogger level
            L.set_level(test_level)
            self.assertEqual(test_level, L._root.level)
            self.assertEqual(0, log.level)

            # Restore and verify
            L.set_level(init_level)
            self.assertEqual(init_level, L._root.level)
            self.assertEqual(0, log.level) 
Example 13
Project: pySmartDL   Author: iTaybb   File: utils.py    License: The Unlicense 6 votes vote down vote up
def create_debugging_logger():
    '''
    Creates a debugging logger that prints to console.
    
    :rtype: `logging.Logger` instance
    '''
    global DEFAULT_LOGGER_CREATED

    t_log = logging.getLogger('pySmartDL')

    if not DEFAULT_LOGGER_CREATED:
        t_log.setLevel(logging.DEBUG)
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        console.setFormatter(logging.Formatter('[%(levelname)s||%(thread)d@{%(pathname)s:%(lineno)d}] %(message)s'))
        t_log.addHandler(console)
        DEFAULT_LOGGER_CREATED = True
    
    return t_log 
Example 14
Project: code2vec   Author: tech-srl   File: config.py    License: MIT License 6 votes vote down vote up
def get_logger(self) -> logging.Logger:
        if self.__logger is None:
            self.__logger = logging.getLogger('code2vec')
            self.__logger.setLevel(logging.INFO)
            self.__logger.handlers = []
            self.__logger.propagate = 0

            formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')

            if self.VERBOSE_MODE >= 1:
                ch = logging.StreamHandler(sys.stdout)
                ch.setLevel(logging.INFO)
                ch.setFormatter(formatter)
                self.__logger.addHandler(ch)

            if self.LOGS_PATH:
                fh = logging.FileHandler(self.LOGS_PATH)
                fh.setLevel(logging.INFO)
                fh.setFormatter(formatter)
                self.__logger.addHandler(fh)

        return self.__logger 
Example 15
Project: modelforge   Author: src-d   File: tools.py    License: Apache License 2.0 6 votes vote down vote up
def install_environment(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger):
    """
    Install the packages mentioned in the model's metadata.

    :param args: :param args: :class:`argparse.Namespace` with "input", "reproduce", "backend", \
                 "args", "username", "password", "remote_repo" and "log_level".
    :param backend: Backend which is responsible for working with model files.
    :param log: Logger supplied by supply_backend
    :return: None
    """
    model = _load_generic_model(args.input, backend, log)
    if model is None:
        return 1
    packages = ["%s==%s" % (pkg, ver) for pkg, ver in model.environment["packages"]]
    cmdline = [sys.executable, "-m", "pip", "install"] + args.pip + packages
    log.info(" ".join(cmdline))
    subprocess.check_call(cmdline)
    if args.reproduce:
        for dataset in model.datasets:
            download_http(dataset[0], dataset[1], log) 
Example 16
Project: modelforge   Author: src-d   File: registry.py    License: Apache License 2.0 6 votes vote down vote up
def initialize_registry(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger):
    """
    Initialize the registry and the index.

    :param args: :class:`argparse.Namespace` with "backend", "args", "force" and "log_level".
    :param backend: Backend which is responsible for working with model files.
    :param log: Logger supplied by supply_backend
    :return: None
    """
    try:
        backend.reset(args.force)
    except ExistingBackendError:
        return 1

    log.info("Resetting the index ...")
    backend.index.reset()
    try:
        backend.index.upload("reset", {})
    except ValueError:
        return 1
    log.info("Successfully initialized") 
Example 17
Project: modelforge   Author: src-d   File: registry.py    License: Apache License 2.0 6 votes vote down vote up
def delete_model(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger):
    """
    Delete a model.

    :param args: :class:`argparse.Namespace` with "input", "backend", "args", "meta", \
                        "update_default", "username", "password", "remote_repo", \
                        "template_model", "template_readme" and "log_level".
    :param backend: Backend which is responsible for working with model files.
    :param log: Logger supplied by supply_backend
    :return: None
    """
    try:
        meta = backend.index.remove_model(args.input)
        template_readme = backend.index.load_template(args.template_readme)
        backend.index.update_readme(template_readme)
    except ValueError:
        return 1
    backend.delete_model(meta)
    log.info("Updating the models index...")
    try:
        backend.index.upload("delete", meta)
    except ValueError:  # TODO: replace with PorcelainError
        return 1
    log.info("Successfully deleted") 
Example 18
Project: incubator-spot   Author: apache   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def get_logger(cls, name, level='INFO', filepath=None, fmt=None):
        '''
            Return a new logger or an existing one, if any.

        :param cls     : The class as implicit first argument.
        :param name    : Return a logger with the specified name.
        :param filepath: Path of the file, where logs will be saved. If it is not set,
                         redirects the log stream to `sys.stdout`.
        :param fmt     : A format string for the message as a whole, as well as a format
                         string for the date/time portion of the message.
                         Default: '%(asctime)s %(levelname)-8s %(name)-34s %(message)s'
        :rtype         : :class:`logging.Logger`
        '''
        logger = logging.getLogger(name)
        # .............................if logger already exists, return it
        if logger.handlers: return logger

        if filepath:
            # .........................rotate log file (1 rotation per 512KB
            handler  = RotatingFileHandler(filepath, maxBytes=524288, backupCount=8)
        else:
            handler  = logging.StreamHandler(sys.stdout)

        fmt = fmt or '%(asctime)s %(levelname)-8s %(name)-34s %(message)s'
        handler.setFormatter(logging.Formatter(fmt))

        try:
            logger.setLevel(getattr(logging, level.upper() if level else 'INFO'))
        except: logger.setLevel(logging.INFO)

        logger.addHandler(handler)
        return logger 
Example 19
Project: drydock   Author: airshipit   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.log = logging.Logger('ingester')
        return 
Example 20
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: MIT License 5 votes vote down vote up
def logger(self, logger):
        """Set a custom logger.

        :param logger: The logger to use
        :type logger: `~logging.Logger` instance

        """
        self._logger = logger 
Example 21
Project: mmdetection   Author: open-mmlab   File: logger.py    License: Apache License 2.0 5 votes vote down vote up
def get_root_logger(log_file=None, log_level=logging.INFO):
    """Get root logger.

    Args:
        log_file (str, optional): File path of log. Defaults to None.
        log_level (int, optional): The level of logger.
            Defaults to logging.INFO.

    Returns:
        :obj:`logging.Logger`: The obtained logger
    """
    logger = get_logger(name='mmdet', log_file=log_file, log_level=log_level)

    return logger 
Example 22
Project: query-exporter   Author: albertodonato   File: loop.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(
        self, config: Config, registry: MetricsRegistry, logger: Logger,
    ):
        self._config = config
        self._registry = registry
        self._logger = logger
        self._timed_queries: List[Query] = []
        self._aperiodic_queries: List[Query] = []
        # map query names to their TimedCalls
        self._timed_calls: Dict[str, TimedCall] = {}
        # map query names to list of database names
        self._doomed_queries: Dict[str, Set[str]] = defaultdict(set)
        self._loop = asyncio.get_event_loop()
        self._setup() 
Example 23
Project: query-exporter   Author: albertodonato   File: db.py    License: GNU General Public License v3.0 5 votes vote down vote up
def set_logger(self, logger: logging.Logger):
        """Set a logger for the DataBase"""
        self._logger = logger 
Example 24
Project: query-exporter   Author: albertodonato   File: config.py    License: GNU General Public License v3.0 5 votes vote down vote up
def load_config(config_fd: IO, logger: Logger, env: Environ = os.environ) -> Config:
    """Load YAML config from file."""
    data = defaultdict(dict, yaml.safe_load(config_fd))
    _validate_config(data)
    databases, database_labels = _get_databases(data["databases"], env)
    extra_labels = frozenset([DATABASE_LABEL]) | database_labels
    metrics = _get_metrics(data["metrics"], extra_labels)
    queries = _get_queries(data["queries"], frozenset(databases), metrics, extra_labels)
    config = Config(databases, metrics, queries)
    _warn_if_unused(config, logger)
    return config 
Example 25
Project: fishroom   Author: tuna   File: helpers.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_logger(name, level=None) -> logging.Logger:
    logging.basicConfig(format='[%(name)s] [%(levelname)s] %(message)s')
    logger = logging.getLogger(name)
    if level is None:
        level = logging.DEBUG if config.get("debug", False) else logging.INFO
    logger.setLevel(level)
    return logger 
Example 26
Project: quart   Author: pgjones   File: app.py    License: MIT License 5 votes vote down vote up
def logger(self) -> Logger:
        """A :class:`logging.Logger` logger for the app.

        This can be used to log messages in a format as defined in the
        app configuration, for example,

        .. code-block:: python

            app.logger.debug("Request method %s", request.method)
            app.logger.error("Error, of some kind")

        """
        if self._logger is None:
            self._logger = create_logger(self)
        return self._logger 
Example 27
Project: botbuilder-python   Author: microsoft   File: bot_framework_http_client.py    License: MIT License 5 votes vote down vote up
def __init__(
        self,
        credential_provider: CredentialProvider,
        channel_provider: ChannelProvider = None,
        logger: Logger = None,
    ):
        if not credential_provider:
            raise TypeError("credential_provider can't be None")

        self._credential_provider = credential_provider
        self._channel_provider = channel_provider
        self._logger = logger
        self._session = aiohttp.ClientSession() 
Example 28
Project: glazier   Author: google   File: log_copy.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self):
    self._logging = logging.Logger('log_copy')
    path = '%s\\log_copy.log' % logs.GetLogsPath()
    self._logging.addHandler(logging.FileHandler(path)) 
Example 29
Project: certidude   Author: laurivosandi   File: __init__.py    License: MIT License 5 votes vote down vote up
def __init__(self):
        app = falcon.API(middleware=NormalizeMiddleware())
        app.req_options.auto_parse_form_urlencoded = True
        self.attach(app)

        # Set up log handlers
        log_handlers = []
        if config.LOGGING_BACKEND == "sql":
            from certidude.mysqllog import LogHandler
            from certidude.api.log import LogResource
            uri = config.cp.get("logging", "database")
            log_handlers.append(LogHandler(uri))
        elif config.LOGGING_BACKEND == "syslog":
            from logging.handlers import SysLogHandler
            log_handlers.append(SysLogHandler())
            # Browsing syslog via HTTP is obviously not possible out of the box
        elif config.LOGGING_BACKEND:
            raise ValueError("Invalid logging.backend = %s" % config.LOGGING_BACKEND)
        from certidude.push import EventSourceLogHandler
        log_handlers.append(EventSourceLogHandler())

        for j in logging.Logger.manager.loggerDict.values():
            if isinstance(j, logging.Logger): # PlaceHolder is what?
                if j.name.startswith("certidude."):
                    j.setLevel(logging.DEBUG)
                    for handler in log_handlers:
                        j.addHandler(handler)

        self.server = make_server("127.0.1.1", self.PORT, app, WSGIServer)
        setproctitle("certidude: %s" % self.NAME) 
Example 30
Project: hyper-h2   Author: python-hyper   File: test_config.py    License: MIT License 5 votes vote down vote up
def test_logger_instance_is_reflected(self):
        """
        The value of ``logger``, when set, is reflected in the value.
        """
        logger = logging.Logger('hyper-h2.test')
        config = h2.config.H2Configuration()
        config.logger = logger
        assert config.logger is logger