# Python logging libraries

Python logging libraries record events from a running program, such as requests, warnings, and errors. Most of them extend the standard logging module that ships with Python. These libraries give developers the records they search when a service fails in production.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Rich](#richhandler) | 579.9M | 57.8K | Apr 2026 | MIT |
| [OpenTelemetry SDK](#opentelemetry-sdk) | 345.7M | Not on GitHub | Oct 2026 | Apache-2.0 |
| [Sentry SDK](#sentry-sdk) | 157.9M | Not on GitHub | Nov 2026 | MIT |
| [structlog](#structlog) | 128.0M | 5.0K | Jun 2026 | MIT OR Apache-2.0 |
| [Python JSON Logger](#python-json-logger) | 106.9M | Not on GitHub | Aug 2026 | BSD-2-Clause |
| [Loguru](#loguru) | 85.4M | 24.2K | Nov 2026 | MIT |
| [colorlog](#colorlog) | 48.6M | Not on GitHub | Jul 2026 | MIT |
| [coloredlogs](#coloredlogs) | 40.2M | Not on GitHub | Jun 2021 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[Rich](#richhandler) has the most monthly downloads in this comparison, at 579.9M, a count that covers the whole Rich package rather than its logging handler alone.

## Capabilities

| Library | Local JSON log rendering | Colored terminal logging | Stdlib Formatter class |
| --- | --- | --- | --- |
| [Rich](#richhandler) | No | Yes | No |
| [OpenTelemetry SDK](#opentelemetry-sdk) | Yes | No | No |
| [Sentry SDK](#sentry-sdk) | No | No | No |
| [structlog](#structlog) | Yes | Yes | Yes |
| [Python JSON Logger](#python-json-logger) | Yes | No | Yes |
| [Loguru](#loguru) | Yes | Yes | No |
| [colorlog](#colorlog) | No | Yes | Yes |
| [coloredlogs](#coloredlogs) | No | Yes | Yes |

## Libraries

### Rich

[GitHub](https://github.com/Textualize/rich) · [PyPI](https://pypi.org/project/rich) · [Docs](https://rich.readthedocs.io/en/stable/logging.html)

Rich renders formatted text, tables, progress bars, and syntax highlighting in the terminal, and its `RichHandler` class is a handler for the standard `logging` module. The handler formats and colorizes each record that `logging` emits. Passing it in the `handlers` list of `logging.basicConfig` changes the output without touching any log call. With `rich_tracebacks` set, exceptions go through Rich's traceback formatter, which shows more context than the built-in one, and `tracebacks_suppress` hides frames from frameworks such as Click.

- Downloads / mo: 579.9M
- Stars: 57.8K
- Last release: 15.0.0
- License: MIT
- Capabilities: [From the Rich docs](https://rich.readthedocs.io/en/stable/logging.html)

**Strengths**

- **Keeps standard logging APIs.** Attach RichHandler to the standard logging configuration.
- **Formats detailed exception tracebacks.** Enable rich_tracebacks to render exceptions through Rich’s traceback formatter.

**Watch out for**

- **Markup is disabled by default.** Enable markup only when log messages intentionally contain Rich markup.

```sh
python3.13 -m pip install rich==15.0.0
```

**fastapi/fastapi-cli** (649 stars)

[fastapi/fastapi-cli](https://github.com/fastapi/fastapi-cli) 

```python
def setup_logging(terminal_width: int | None = None, level: int = logging.INFO) -> None:
    logger = logging.getLogger("fastapi_cli")
    console = Console(width=terminal_width) if terminal_width else None
    rich_handler = RichHandler(
        show_time=False,
        rich_tracebacks=True,
        tracebacks_show_locals=True,
        markup=True,
        show_path=False,
        console=console,
    )
    rich_handler.setFormatter(logging.Formatter("%(message)s"))
    logger.addHandler(rich_handler)

    logger.setLevel(level)
    logger.propagate = False
```

[src/fastapi_cli/logging.py](https://github.com/fastapi/fastapi-cli/blob/a93728649bbab4f26a5216f420066695d3b2ee00/src/fastapi_cli/logging.py) · [More projects using Rich →](https://dashboard.exa.ai/playground/search?q=Public%20Python%20projects%20using%20rich%20for%20logging%20configuration%2C%20request%20context%2C%20structured%20events%20and%20exception%20output&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import logging
from rich.logging import RichHandler

FORMAT = "%(message)s"
logging.basicConfig(
    level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]
)

log = logging.getLogger("rich")
log.info("Hello, World!")

```

From [logging.html](https://rich.readthedocs.io/en/stable/logging.html)

### OpenTelemetry SDK

[GitHub](https://github.com/open-telemetry/opentelemetry-python) · [PyPI](https://pypi.org/project/opentelemetry-sdk) · [Docs](https://opentelemetry-python.readthedocs.io/en/latest/sdk/_logs.html)

The OpenTelemetry SDK is the Python implementation of OpenTelemetry for traces, metrics, and logs. For logs, `LoggingHandler` attaches to the standard `logging` module and writes each record in OTLP, the OpenTelemetry protocol. Processors such as `BatchLogRecordProcessor` pass records to an exporter. `ConsoleLogRecordExporter` prints them for debugging, while sending them to a collector over HTTP or gRPC takes a separate exporter package, such as `opentelemetry-exporter-otlp-proto-http`.

- Downloads / mo: 345.7M
- Last release: 1.45.2
- License: Apache-2.0
- Capabilities: [From the OpenTelemetry SDK docs](https://opentelemetry-python.readthedocs.io/en/latest/sdk/_logs.html)

**Strengths**

- **Writes OTLP records.** LoggingHandler sends standard logging records to a network destination or a file in OTLP format.

```sh
python3.13 -m pip install opentelemetry-sdk==1.45.2
```

**openlit/openlit** (3.1K stars)

[openlit/openlit](https://github.com/openlit/openlit) 

```python
def setup_events(
    application_name,
    environment,
    event_logger,
    otlp_endpoint,
    otlp_headers,
    disable_batch,
):
    """Setup OpenTelemetry events with the given configuration.

    Args:
        application_name: Name of the application
        environment: Deployment environment
        event_logger: Optional pre-configured Logger instance
        otlp_endpoint: Optional OTLP endpoint for exporter
        otlp_headers: Optional headers for OTLP exporter

    Returns:
        Logger: The configured OTel Logger for emitting events as LogRecords
    """
    # If an external events_logger is provided, return it immediately.
    if event_logger:
        return event_logger

    # Proceed with setting up a new events or configuration only if EVENTS_SET is False.
    global EVENTS_SET

    try:
        if not EVENTS_SET:
            existing_provider = _logs.get_logger_provider()

            if isinstance(existing_provider, SDKLoggerProvider):
                logger.info("Detected existing LoggerProvider, reusing it")
            else:
                # No SDK provider configured yet -- create one.
                resource = Resource.create(
                    attributes={
                        SERVICE_NAME: application_name,
                        DEPLOYMENT_ENVIRONMENT: environment,
                        TELEMETRY_SDK_NAME: "openlit",
                    }
                )

                logger_provider = SDKLoggerProvider(resource=resource)

                if otlp_endpoint is not None:
                    os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = otlp_endpoint

                if otlp_headers is not None:
                    if isinstance(otlp_headers, dict):
                        headers_str = ",".join(
                            f"{key}={value}" for key, value in otlp_headers.items()
                        )
                    else:
                        headers_str = otlp_headers

                    os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = headers_str

                exporters_config = parse_exporters("OTEL_LOGS_EXPORTER")
                processors_added = False

                if exporters_config is not None:
                    for exporter_name in exporters_config:
                        if exporter_name == "otlp":
                            event_exporter = OTLPLogExporter()
                            log_processor = (
                                BatchLogRecordProcessor(event_exporter)
                                if not disable_batch
                                else SimpleLogRecordProcessor(event_exporter)
                            )
                            logger_provider.add_log_record_processor(log_processor)
                            processors_added = True
                        elif exporter_name == "console":
                            event_exporter = ConsoleLogRecordExporter()
                            log_processor = SimpleLogRecordProcessor(event_exporter)
                            logger_provider.add_log_record_processor(log_processor)
                            processors_added = True
                        elif exporter_name == "none":
                            continue
                        else:
                            logger.warning("Unknown log exporter: %s", exporter_name)

                    if not processors_added:
                        logger.warning(
                            "OTEL_LOGS_EXPORTER is set but no valid exporters "
                            "configured. Log export is disabled. "
                            "Valid exporters: otlp, console"
                        )
                else:
                    if os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT"):
                        event_exporter = OTLPLogExporter()
                        # pylint: disable=line-too-long
                        log_processor = (
                            BatchLogRecordProcessor(event_exporter)
                            if not disable_batch
                            else SimpleLogRecordProcessor(event_exporter)
                        )
                    else:
                        event_exporter = ConsoleLogRecordExporter()
                        log_processor = SimpleLogRecordProcessor(event_exporter)

                    logger_provider.add_log_record_processor(log_processor)

                _logs.set_logger_provider(logger_provider)

            EVENTS_SET = True

        return _logs.get_logger(__name__)

    except Exception as e:
        logger.error("Failed to setup OpenTelemetry events: %s", e, exc_info=True)
        return None
```

[sdk/python/src/openlit/otel/events.py](https://github.com/openlit/openlit/blob/40bbb4af37ecaa69de1f2d889a7995043f1f35ae/sdk/python/src/openlit/otel/events.py) · [More projects using OpenTelemetry SDK →](https://dashboard.exa.ai/playground/search?q=opentelemetry-sdk%20GitHub%20projects)

**Quickstart**

```python
from opentelemetry.sdk._logs import LoggerProvider
from opentelemetry.sdk._logs.export import ConsoleLogRecordExporter, SimpleLogRecordProcessor

provider = LoggerProvider()
provider.add_log_record_processor(SimpleLogRecordProcessor(ConsoleLogRecordExporter()))
provider.get_logger("example").emit(body="Hello", severity_text="INFO")
provider.shutdown()
```

From [_logs.html](https://opentelemetry-python.readthedocs.io/en/latest/sdk/_logs.html)

### Sentry SDK

[GitHub](https://github.com/getsentry/sentry-python) · [PyPI](https://pypi.org/project/sentry-sdk) · [Docs](https://docs.sentry.io/platforms/python/logs/)

The Sentry SDK reports errors and logs from a Python application to Sentry, a hosted error tracking service. After `sentry_sdk.init` runs with a project DSN, the `sentry_sdk.logger` namespace sends structured messages whose placeholders, such as `{user_id}`, become searchable attributes. The `LoggingIntegration` captures records from the standard `logging` module as Sentry logs and breadcrumbs. Records at error level and above can also become error events through the `event_level` option.

- Downloads / mo: 157.9M
- Last release: 2.75.0
- License: MIT
- Capabilities: [From the Sentry SDK docs](https://docs.sentry.io/platforms/python/logs/)

**Strengths**

- **Searchable by attribute.** Logs appear beside related errors and can be searched by text or by individual attributes.

**Watch out for**

- **Recent SDK required.** Logs need Sentry Python SDK 2.35.0 or later.

```sh
python3.13 -m pip install sentry-sdk==2.75.0
```

**nuclia/nucliadb** (723 stars)

[nuclia/nucliadb](https://github.com/nuclia/nucliadb) 

```python
def setup_error_handling(version: str) -> None:
    settings = ErrorHandlingSettings()

    if settings.sentry_url:
        # Disabled everywhere for now. Let's have less knobs to tweak.
        # Either we use with with sentry or we don't.
        # enabled_integrations: list[Any] = [
        #     LoggingIntegration(level=logging.CRITICAL, event_level=logging.CRITICAL)
        # ]

        sentry_sdk.init(
            release=version,
            environment=settings.environment,
            dsn=settings.sentry_url,
            integrations=[
                LoggingIntegration(
                    level=None,
                ),
            ],
        )
        sentry_sdk.set_tag("zone", settings.zone)
```

[nucliadb_telemetry/src/nucliadb_telemetry/errors.py](https://github.com/nuclia/nucliadb/blob/514c0fca39afa36d80d74dd60cf865a65dc3639e/nucliadb_telemetry/src/nucliadb_telemetry/errors.py) · [More projects using Sentry SDK →](https://dashboard.exa.ai/playground/search?q=sentry-sdk%20GitHub%20projects)

**Quickstart**

```python
import sentry_sdk

sentry_sdk.init(dsn="https://<key>@o<orgId>.ingest.sentry.io/<projectId>", enable_logs=True)
sentry_sdk.logger.info("Hello")
sentry_sdk.flush()
```

From [index.html](https://docs.sentry.io/platforms/python/logs/)

### structlog

[GitHub](https://github.com/hynek/structlog) · [PyPI](https://pypi.org/project/structlog) · [Docs](https://www.structlog.org/en/stable/getting-started.html)

structlog builds each log entry as a dictionary of key and value pairs, called an event. A configured chain of processors adds fields such as the level and a timestamp, then a renderer turns the event into JSON, logfmt, or colored console text. `structlog.get_logger` works with no setup and prints to standard output. Values bound once with `bind` or through context variables appear on every later event. The final output can also go through the standard `logging` module.

- Downloads / mo: 128.0M
- Stars: 5.0K
- Last release: 26.1.0
- License: MIT OR Apache-2.0
- Capabilities: [From the structlog docs](https://www.structlog.org/en/stable/getting-started.html)

**Strengths**

- **Processes structured event dictionaries.** Choose processors and a renderer for the desired event output.
- **Binds request-local log context.** Merge context variables into events and bind request fields once.

**Watch out for**

- **Request context needs explicit reset.** Clear context variables at request entry before binding the next request’s fields.

```sh
python3.13 -m pip install structlog==26.1.0
```

**jrobichaud/django-structlog** (530 stars)

[jrobichaud/django-structlog](https://github.com/jrobichaud/django-structlog) 

```python
async def async_streaming_content_wrapper(
    streaming_content: AsyncIterator[bytes], context: Any
) -> AsyncGenerator[bytes, Any]:
    with structlog.contextvars.bound_contextvars(**context):
        logger.log(app_settings.REQUEST_STARTED_LOG_LEVEL, "streaming_started")
        try:
            async for chunk in streaming_content:
                yield chunk
        except asyncio.CancelledError:
            logger.log(app_settings.REQUEST_CANCELLED_LOG_LEVEL, "streaming_cancelled")
            raise
        except Exception:
            logger.exception("streaming_failed")
            raise
        else:
            logger.log(app_settings.STATUS_2XX_LOG_LEVEL, "streaming_finished")
```

[django_structlog/middlewares/request.py](https://github.com/jrobichaud/django-structlog/blob/37617a65b2af9efcb7099c22db0bc1a06415d745/django_structlog/middlewares/request.py) · [More projects using structlog →](https://dashboard.exa.ai/playground/search?q=Public%20Python%20projects%20using%20structlog%20for%20logging%20configuration%2C%20request%20context%2C%20structured%20events%20and%20exception%20output&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import structlog
log = structlog.get_logger()
log.info("hello, %s!", "world", key="value!", more_than_strings=[1, 2, 3])
```

From [getting-started.html](https://www.structlog.org/en/stable/getting-started.html)

### Python JSON Logger

[GitHub](https://github.com/nhairs/python-json-logger) · [PyPI](https://pypi.org/project/python-json-logger) · [Docs](https://nhairs.github.io/python-json-logger/latest/quickstart/)

Python JSON Logger supplies formatter classes for the standard `logging` module that encode each record as JSON. `JsonFormatter` attaches to any existing handler through `setFormatter`. The `fmt` argument sets the fields and accepts the same format styles as `logging`. Messages can also be dictionaries, and values passed through `extra` become fields of the JSON object.

- Downloads / mo: 106.9M
- Last release: 4.2.0
- License: BSD-2-Clause
- Capabilities: [From the Python JSON Logger docs](https://nhairs.github.io/python-json-logger/latest/quickstart/)

**Strengths**

- **Plugs into existing handlers.** The formatter attaches to a standard logging handler, and existing log calls stay unchanged.

```sh
python3.13 -m pip install python-json-logger==4.2.0
```

**PrefectHQ/prefect** (24.2K stars)

[PrefectHQ/prefect](https://github.com/PrefectHQ/prefect) 

```python
def add_fields(
    self,
    log_record: dict[str, object],
    record: logging.LogRecord,
    message_dict: dict[str, object],
) -> None:
    super().add_fields(log_record, record, message_dict)

    if self._refkey and hasattr(record, "k8s_ref"):
        ref = getattr(record, "k8s_ref")
        log_record[self._refkey] = ref

    if "severity" not in log_record:
        log_record["severity"] = (
            "debug"
            if record.levelno <= logging.DEBUG
            else "info"
            if record.levelno <= logging.INFO
            else "warn"
            if record.levelno <= logging.WARNING
            else "error"
            if record.levelno <= logging.ERROR
            else "fatal"
        )
```

[src/integrations/prefect-kubernetes/prefect_kubernetes/_logging.py](https://github.com/PrefectHQ/prefect/blob/ec4b188a19371cb79bc91afe897042bca3a3c95f/src/integrations/prefect-kubernetes/prefect_kubernetes/_logging.py) · [More projects using Python JSON Logger →](https://dashboard.exa.ai/playground/search?q=python-json-logger%20GitHub%20projects)

**Quickstart**

```python
import logging
from pythonjsonlogger.json import JsonFormatter

logger = logging.getLogger()

logHandler = logging.StreamHandler()
formatter = JsonFormatter()
logHandler.setFormatter(formatter)
logger.addHandler(logHandler)

logger.warning("Hello")
```

From [quickstart.md](https://nhairs.github.io/python-json-logger/latest/quickstart/)

### Loguru

[GitHub](https://github.com/Delgan/loguru) · [PyPI](https://pypi.org/project/loguru) · [Docs](https://pypi.org/pypi/loguru/0.8.0/json)

Loguru replaces the setup of the standard `logging` module with one preconfigured `logger` that writes to standard error on import. The `add` method registers each destination, called a sink, which can be a file path, a function, a file object, or a standard `logging` handler. File sinks take rotation, retention, and compression settings. With `serialize` set, each record reaches the sink as a JSON string, and `bind` attaches fields to later messages.

- Downloads / mo: 85.4M
- Stars: 24.2K
- Last release: 0.8.0
- License: MIT
- Capabilities: [From the Loguru docs](https://pypi.org/pypi/loguru/0.8.0/json)

**Strengths**

- **Manages rotating log sinks.** Configure file rotation, retention, and compression on the logger.
- **Serializes structured log events.** Enable serialize to send JSON-formatted records to the configured sink.

**Watch out for**

- **Diagnostics include variable values.** Set diagnose=False when production tracebacks must omit local variable values.

```sh
python3.13 -m pip install loguru==0.8.0
```

**FoundationAgents/MetaGPT** (71.3K stars)

[FoundationAgents/MetaGPT](https://github.com/FoundationAgents/MetaGPT) 

```python
def define_log_level(print_level="INFO", logfile_level="DEBUG", name: str = None):
    """Adjust the log level to above level"""
    global _print_level
    _print_level = print_level

    current_date = datetime.now()
    formatted_date = current_date.strftime("%Y%m%d")
    log_name = f"{name}_{formatted_date}" if name else formatted_date  # name a log with prefix name

    _logger.remove()
    _logger.add(sys.stderr, level=print_level)
    _logger.add(METAGPT_ROOT / f"logs/{log_name}.txt", level=logfile_level)
    return _logger
```

[metagpt/logs.py](https://github.com/FoundationAgents/MetaGPT/blob/11cdf466d042aece04fc6cfd13b28e1a70341b1f/metagpt/logs.py) · [More projects using Loguru →](https://dashboard.exa.ai/playground/search?q=Public%20Python%20projects%20using%20loguru%20for%20logging%20configuration%2C%20request%20context%2C%20structured%20events%20and%20exception%20output&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from loguru import logger

logger.debug("That's it, beautiful and simple logging!")
```

From [README.md](https://pypi.org/pypi/loguru/0.8.0/json)

### colorlog

[GitHub](https://github.com/borntyping/python-colorlog) · [PyPI](https://pypi.org/project/colorlog) · [Docs](https://pypi.org/pypi/colorlog/6.12.0/json)

colorlog adds color to the output of the standard `logging` module. Its `ColoredFormatter` class extends `logging.Formatter` and replaces the formatter on any existing handler. A `log_colors` mapping assigns a color to each level name, and `secondary_log_colors` colors other parts of the format string. On Windows, colorama installs as a dependency so that the colors display.

- Downloads / mo: 48.6M
- Last release: 6.12.0
- License: MIT
- Capabilities: [From the colorlog docs](https://pypi.org/pypi/colorlog/6.12.0/json)

**Strengths**

- **Extends logging.Formatter.** ColoredFormatter replaces the formatter on any standard logging handler.

**Watch out for**

- **Color off outside terminals.** Colors turn off on output that is not a terminal unless force_color is set.

```sh
python3.13 -m pip install colorlog==6.12.0
```

**optuna/optuna** (15.1K stars)

[optuna/optuna](https://github.com/optuna/optuna) 

```python
def create_default_formatter() -> logging.Formatter:
    """Create a default formatter of log messages.

    This function is not supposed to be directly accessed by library users.
    """
    header = "[%(levelname)1.1s %(asctime)s]"
    message = "%(message)s"
    return colorlog.TTYColoredFormatter(
        f"%(log_color)s{header}%(reset)s {message}",
        stream=sys.stderr,
    )

```

[optuna/logging.py](https://github.com/optuna/optuna/blob/0abf066c1e5d9d83987986869daa3c2bb23df519/optuna/logging.py#L31-L41) · [More projects using colorlog →](https://dashboard.exa.ai/playground/search?q=colorlog%20GitHub%20projects)

**Quickstart**

```python
import logging
import colorlog

handler = colorlog.StreamHandler()
handler.setFormatter(colorlog.ColoredFormatter("%(log_color)s%(levelname)s:%(name)s:%(message)s"))
logger = colorlog.getLogger("example")
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.info("Hello")
```

From [README.md](https://pypi.org/pypi/colorlog/6.12.0/json)

### coloredlogs

[GitHub](https://github.com/xolox/python-coloredlogs) · [PyPI](https://pypi.org/project/coloredlogs) · [Docs](https://coloredlogs.readthedocs.io/en/latest/api.html)

coloredlogs colors terminal output from the standard `logging` module with ANSI escape sequences. One call to `coloredlogs.install` adds a colored handler to the root logger. The `ColoredFormatter` class inherits from `logging.Formatter` for setups that attach their own handlers. On Windows, the package tries native ANSI support first and falls back on colorama when it is installed.

- Downloads / mo: 40.2M
- Last release: 15.0.1
- License: MIT
- Capabilities: [From the coloredlogs docs](https://coloredlogs.readthedocs.io/en/latest/api.html)

**Strengths**

- **One-call setup.** coloredlogs.install adds a colored handler to the root logger, which also colors messages from other libraries.

```sh
python3.13 -m pip install coloredlogs==15.0.1
```

**nccgroup/ScoutSuite** (7.9K stars)

[nccgroup/ScoutSuite](https://github.com/nccgroup/ScoutSuite) 

```python
def set_logger_configuration(is_debug=False, quiet=False, output_file_path=None):
    """
    Configure whether full stacktraces should be dumped in the console output
    """

    # set debug level
    global verbose_exceptions
    verbose_exceptions = is_debug

    # if "quiet" is set, don't output anything
    if quiet:
        coloredlogs.install(level='ERROR', logger=logger)
    else:
        coloredlogs.install(level='DEBUG' if is_debug else 'INFO', logger=logger)

    if output_file_path:
        # For some reason, hostname information is not passed to the FileHandler
        # Add it using a filter
        class HostnameFilter(logging.Filter):
            hostname = platform.node()

            def filter(self, record):
                record.hostname = HostnameFilter.hostname
                return True

        # create file handler which logs messages
        fh = logging.FileHandler(output_file_path, 'w+')
        # Add filter to add hostname information
        fh.addFilter(HostnameFilter())
        # create formatter and add it to the handlers
        formatter = logging.Formatter(fmt='%(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s',
                                      datefmt='%Y-%m-%d %H:%M:%S')
        fh.setFormatter(formatter)
        # add the handlers to the logger
        logger.addHandler(fh)
```

[ScoutSuite/core/console.py](https://github.com/nccgroup/ScoutSuite/blob/7909f2fc6186063e5c9e7ddef8c4d7d1072c8f3d/ScoutSuite/core/console.py) · [More projects using coloredlogs →](https://dashboard.exa.ai/playground/search?q=coloredlogs%20GitHub%20projects)

**Quickstart**

```python
import coloredlogs, logging

coloredlogs.install(level="DEBUG")
logger = logging.getLogger("some.module.name")
logger.info("this is an informational message")
```

From [api.html](https://coloredlogs.readthedocs.io/en/latest/api.html)

## FAQ

### Which Python logging library should I use?

The standard `logging` module ships with Python, and most libraries here plug into it. [Rich](#richhandler), [colorlog](#colorlog), and [coloredlogs](#coloredlogs) add color, and [Python JSON Logger](#python-json-logger) adds JSON, with no change to existing log calls. [Loguru](#loguru) and [structlog](#structlog) replace the setup with their own logger API.

### Loguru vs logging: what is the difference?

Loguru provides one preconfigured `logger`, and its `add` method registers each output, called a sink, in place of the handlers, formatters, and filters that `logging` uses. File sinks take rotation, retention, and compression settings directly.

### structlog vs Loguru: which should I use?

structlog builds each event as a dictionary that passes through a chain of processors, then renders JSON, logfmt, or console output, or hands the event to `logging`. Loguru keeps a single logger that sends message records to sinks, and writes JSON when a sink sets `serialize`.

### How do I log JSON in Python?

[Python JSON Logger](#python-json-logger) adds a JSON formatter to existing `logging` handlers. [structlog](#structlog) renders JSON with `JSONRenderer`, and [Loguru](#loguru) writes JSON when a sink sets `serialize`.

### How do I use Rich with Python logging?

Pass `RichHandler()` in the `handlers` list of `logging.basicConfig`. Setting `rich_tracebacks` on the handler formats exceptions with Rich's traceback renderer.

### Can Python log files rotate by size or time?

The standard library includes `RotatingFileHandler` for size and `TimedRotatingFileHandler` for time. [Loguru](#loguru) takes a `rotation` setting on each file sink.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python logging libraries logging Loguru structlog RichHandler code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
