Python loguru.logger.enable() Examples

The following are 20 code examples of loguru.logger.enable(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module loguru.logger , or try the search function .
Example #1
Source File: console.py    From CharGer with GNU General Public License v3.0 7 votes vote down vote up
def setup_logger() -> None:
    """Set up stderr logging format.

    The logging format and colors can be overridden by setting up the
    environment variables such as ``LOGURU_FORMAT``.
    See `Loguru documentation`_ for details.

    .. _Loguru documentation: https://loguru.readthedocs.io/en/stable/api/logger.html#env
    """
    logger.remove()  # Remove the default setting

    # Set up the preferred logging colors and format unless overridden by its environment variable
    logger.level("INFO", color=environ.get("LOGURU_INFO_COLOR") or "<white>")
    logger.level("DEBUG", color=environ.get("LOGURU_DEBUG_COLOR") or "<d><white>")
    log_format = environ.get("LOGURU_FORMAT") or (
        # "<green>{time:YYYY-MM-DD HH:mm:ss}</green> "
        "<b><level>{level: <8}</level></b> "
        "| <level>{message}</level>"
    )
    logger.add(sys.stderr, format=log_format)

    # By default all the logging messages are disabled
    logger.enable("charger") 
Example #2
Source File: _logger.py    From SimpleSQLite with MIT License 6 votes vote down vote up
def set_logger(is_enable: bool, propagation_depth: int = 2) -> None:
    if is_enable:
        logger.enable(MODULE_NAME)
    else:
        logger.disable(MODULE_NAME)

    if propagation_depth <= 0:
        return

    tabledata.set_logger(is_enable, propagation_depth - 1)
    sqliteschema.set_logger(is_enable, propagation_depth - 1)

    try:
        import pytablereader

        pytablereader.set_logger(is_enable, propagation_depth - 1)
    except (ImportError, TypeError):
        pass 
Example #3
Source File: __main__.py    From sqlitebiter with MIT License 6 votes vote down vote up
def initialize_logger(name: str, log_level: str) -> None:
    logger.remove()

    if log_level == QUIET_LOG_LEVEL:
        logger.disable(name)
        return

    if log_level == "DEBUG":
        log_format = (
            "<level>{level: <8}</level> | "
            "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
        )
    else:
        log_format = "<level>[{level}]</level> {message}"

    logger.add(sys.stdout, colorize=True, format=log_format, level=log_level)
    logger.enable(name)
    ptr.set_logger(True)
    sqlite.set_logger(True)
    appconfigpy.set_logger(True) 
Example #4
Source File: _logger.py    From pytablereader with MIT License 6 votes vote down vote up
def set_logger(is_enable, propagation_depth=2):
    if is_enable:
        logger.enable(MODULE_NAME)
    else:
        logger.disable(MODULE_NAME)

    if propagation_depth <= 0:
        return

    dataproperty.set_logger(is_enable, propagation_depth - 1)

    try:
        import simplesqlite

        simplesqlite.set_logger(is_enable, propagation_depth - 1)
    except (ImportError, TypeError):
        pass 
Example #5
Source File: _logger.py    From pytablewriter with MIT License 6 votes vote down vote up
def set_logger(is_enable: bool, propagation_depth: int = 1) -> None:
    if is_enable:
        logger.enable(MODULE_NAME)
    else:
        logger.disable(MODULE_NAME)

    if propagation_depth <= 0:
        return

    dataproperty.set_logger(is_enable, propagation_depth - 1)

    try:
        import simplesqlite

        simplesqlite.set_logger(is_enable, propagation_depth - 1)
    except ImportError:
        pass

    try:
        import pytablereader

        pytablereader.set_logger(is_enable, propagation_depth - 1)
    except ImportError:
        pass 
Example #6
Source File: _logger.py    From pingparsing with MIT License 5 votes vote down vote up
def set_logger(is_enable: bool, propagation_depth: int = 1) -> None:
    if is_enable:
        logger.enable(MODULE_NAME)
    else:
        logger.disable(MODULE_NAME)

    if propagation_depth <= 0:
        return

    subprocrunner.set_logger(is_enable, propagation_depth - 1) 
Example #7
Source File: _logger.py    From pingparsing with MIT License 5 votes vote down vote up
def enable(self, name):  # pragma: no cover
        pass 
Example #8
Source File: test_activation.py    From loguru with MIT License 5 votes vote down vote up
def test_invalid_enable_name(name):
    with pytest.raises(TypeError):
        logger.enable(name) 
Example #9
Source File: test_activation.py    From loguru with MIT License 5 votes vote down vote up
def test_f_globals_name_absent_with_others(writer, f_globals_name_absent):
    logger.add(writer, format="{message}")
    logger.info("1")
    logger.enable(None)
    logger.disable("foobar")
    logger.enable("foo.bar")
    logger.disable(None)
    logger.info("2")
    logger.enable("foobar")
    logger.enable(None)
    logger.info("3")
    assert writer.read() == "1\n3\n" 
Example #10
Source File: test_activation.py    From loguru with MIT License 5 votes vote down vote up
def test_log_before_enable_f_globals_name_absent(writer, f_globals_name_absent):
    logger.add(writer, format="{message}")
    logger.disable(None)
    logger.debug("nope")
    logger.enable(None)
    logger.debug("yes")
    result = writer.read()
    assert result == "yes\n" 
Example #11
Source File: test_activation.py    From loguru with MIT License 5 votes vote down vote up
def test_multiple_activations():
    n = lambda: len(logger._core.activation_list)

    assert n() == 0
    logger.enable("")
    assert n() == 0
    logger.disable("")
    assert n() == 1
    logger.enable("foo")
    assert n() == 2
    logger.enable("foo.bar")
    assert n() == 2
    logger.disable("foo")
    assert n() == 1
    logger.disable("foo.bar")
    assert n() == 1
    logger.enable("foo.bar")
    assert n() == 2
    logger.disable("foo.bar.baz")
    assert n() == 3
    logger.disable("foo.baz")
    assert n() == 3
    logger.disable("foo.baz.bar")
    assert n() == 3
    logger.enable("foo.baz.bar")
    assert n() == 4
    logger.enable("")
    assert n() == 0 
Example #12
Source File: test_activation.py    From loguru with MIT License 5 votes vote down vote up
def test_log_before_disable(writer):
    logger.add(writer, format="{message}")
    logger.enable("")
    logger.debug("yes")
    logger.disable("tests")
    logger.debug("nope")
    result = writer.read()
    assert result == "yes\n" 
Example #13
Source File: test_activation.py    From loguru with MIT License 5 votes vote down vote up
def test_log_before_enable(writer):
    logger.add(writer, format="{message}")
    logger.disable("")
    logger.debug("nope")
    logger.enable("tests")
    logger.debug("yes")
    result = writer.read()
    assert result == "yes\n" 
Example #14
Source File: test_activation.py    From loguru with MIT License 5 votes vote down vote up
def test_enable(writer, name, should_log):
    logger.add(writer, format="{message}")
    logger.disable("")
    logger.enable(name)
    logger.debug("message")
    result = writer.read()

    if should_log:
        assert result == "message\n"
    else:
        assert result == "" 
Example #15
Source File: __init__.py    From aria2p with ISC License 5 votes vote down vote up
def enable_logger(sink=sys.stderr, level="WARNING"):
    """
    Enable the logging of messages.

    Configure the ``logger`` variable imported from ``loguru``.

    Args:
        sink (file): An opened file pointer, or stream handler. Default to standard error.
        level (str): The log level to use. Possible values are TRACE, DEBUG, INFO, WARNING, ERROR, CRITICAL.
            Default to WARNING.
    """
    logger.remove()
    logger.configure(handlers=[{"sink": sink, "level": level}])
    logger.enable("aria2p") 
Example #16
Source File: run.py    From ScaffoldGraph with MIT License 5 votes vote down vote up
def configure_logger(verbosity):
    """Configure the scaffoldgraph cli logger to use tqdm handler"""

    config = {'handlers': []}
    logger.enable('scaffoldgraph')

    if verbosity == 0:
        tqdm_handler['sink'].level = logging.CRITICAL
        tqdm_handler['level'] = 'CRITICAL'
    elif verbosity == 1:
        tqdm_handler['sink'].level = logging.ERROR
        tqdm_handler['level'] = 'ERROR'
    elif verbosity == 2:
        tqdm_handler['sink'].level = logging.WARNING
        tqdm_handler['level'] = 'WARNING'
    elif verbosity == 3:
        tqdm_handler['sink'].level = logging.INFO
        tqdm_handler['level'] = 'INFO'
    elif verbosity == 4:
        tqdm_handler['sink'].level = logging.DEBUG
        tqdm_handler['level'] = 'DEBUG'
    else:  # if < 0 or > 4 is supplied set logger to max level (DEBUG)
        tqdm_handler['sink'].level = logging.DEBUG
        tqdm_handler['level'] = 'DEBUG'

    config["handlers"].append(tqdm_handler)
    logger.configure(**config) 
Example #17
Source File: _logger.py    From tcconfig with MIT License 5 votes vote down vote up
def set_logger(is_enable):
    if is_enable:
        logger.enable(MODULE_NAME)
    else:
        logger.disable(MODULE_NAME)

    simplesqlite.set_logger(is_enable)
    subprocrunner.set_logger(is_enable) 
Example #18
Source File: conftest.py    From CharGer with GNU General Public License v3.0 5 votes vote down vote up
def caplog(_caplog):  # noqa: F811
    """A fixture to capture loguru logging messages.

    Copied from https://loguru.readthedocs.io/en/stable/resources/migration.html
    """

    class PropagateHandler(logging.Handler):
        def emit(self, record):
            logging.getLogger(record.name).handle(record)

    logger.enable("charger")
    handler_id = logger.add(PropagateHandler(), format="{message}")
    yield _caplog
    logger.remove(handler_id)
    logger.disable("charger") 
Example #19
Source File: logs.py    From veros with MIT License 4 votes vote down vote up
def setup_logging(loglevel='info', stream_sink=sys.stdout):
    from . import runtime_state, runtime_settings

    handler_conf = dict(
        sink=stream_sink,
        level=loglevel.upper(),
        colorize=sys.stdout.isatty(),
    )

    logger.level('TRACE', color='<dim>')
    logger.level('DEBUG', color='<dim><cyan>')
    logger.level('INFO', color='')
    logger.level('SUCCESS', color='<dim><green>')
    logger.level('WARNING', color='<yellow>')
    logger.level('ERROR', color='<bold><red>')
    logger.level('DIAGNOSTIC', color='<bold><yellow>')
    logger.level('CRITICAL', color='<bold><red><WHITE>')

    if runtime_settings.log_all_processes:
        handler_conf.update(
            format=f'{runtime_state.proc_rank} | <level>{{message}}</level>'
        )
    else:
        handler_conf.update(
            format='<level>{message}</level>',
            filter=lambda record: runtime_state.proc_rank == 0
        )

    def diagnostic(_, message, *args, **kwargs):
        logger.opt(depth=1).log('DIAGNOSTIC', message, *args, **kwargs)

    logger.__class__.diagnostic = diagnostic

    def showwarning(message, cls, source, lineno, *args):
        logger.warning(
            '{warning}: {message} ({source}:{lineno})',
            message=message,
            warning=cls.__name__,
            source=source,
            lineno=lineno
        )

    warnings.showwarning = showwarning

    veros_logger = logger.configure(handlers=[handler_conf])
    logger.enable('veros')

    return veros_logger 
Example #20
Source File: config.py    From google-music-scripts with MIT License 4 votes vote down vote up
def configure_logging(
	modifier=0,
	*,
	username=None,
	debug=False,
	log_to_stdout=True,
	log_to_file=False
):
	logger.remove()

	if debug:
		logger.enable('audio_metadata')
		logger.enable('google_music')
		logger.enable('google_music-proto')
		logger.enable('google_music_utils')

	verbosity = 3 + modifier

	if verbosity < 0:
		verbosity = 0
	elif verbosity > 8:
		verbosity = 8

	log_level = VERBOSITY_LOG_LEVELS[verbosity]

	if log_to_stdout:
		logger.add(
			sys.stdout,
			level=log_level,
			format=LOG_FORMAT,
			backtrace=False
		)

	if log_to_file:
		log_dir = ensure_log_dir(username=username)
		log_file = (log_dir / time.strftime('%Y-%m-%d_%H-%M-%S')).with_suffix('.log')

		logger.success("Logging to file: {}", log_file)

		logger.add(
			log_file,
			level=log_level,
			format=LOG_FORMAT,
			backtrace=False,
			encoding='utf8',
			newline='\n'
		)