Skip to main content

Limit excessive log output with Python's standard logging framework.

Project description

log-rate-limit - limit excessive log output

PyPI Version Build Status Code Coverage Checked with mypy Formatted with black

A logging filter using Python's standard logging mechanisms to rate-limit logs - i.e. suppress logs when they are being output too fast.

Log commands are grouped into separate streams that will each have their own rate limitation applied without affecting the logs in other streams. By default every log is assigned a unique stream so that only "repeated" logs will be suppressed (in this case "repeated" logs doesn't mean identical log messages, but rather logs output from the same line of code). However, logs can also be assigned streams manually to achieve various outcomes:

  • A dynamic stream ID based on the message content can be used so that different messages from the same log command can also be rate-limited separately.
  • A log can be assigned to an undefined/None stream so that rate-limiting doesn't apply to it.
  • Logs in different parts of the code can be grouped into the same stream so that they share a rate-limit, e.g. when they all trigger due to the same issue and only some are needed to indicate it.

Usage

Rate-limiting by default

Example of rate-limiting with default options where each log is assigned to it's own stream:

import time
import logging
from log_rate_limit import StreamRateLimitFilter, RateLimit
# Setup logging
logging.basicConfig()
logger = logging.getLogger(__name__)

# Add our filter
logger.addFilter(StreamRateLimitFilter(period_sec=1))
# Log many warnings
for _ in range(100):
    logger.warning("Wolf!")
for i in range(100):
    logger.warning("No really, a wolf!")
    if i == 98:
        time.sleep(1)
# Override stream as undefined to prevent rate-limiting
for _ in range(3):
    logger.warning("Sheep!", extra=RateLimit(stream_id=None))

Which only outputs the following:

WARNING:__main__:Wolf!
WARNING:__main__:No really, a wolf!
WARNING:__main__:No really, a wolf!
+ skipped 98 logs due to rate-limiting
WARNING:__main__:Sheep!
WARNING:__main__:Sheep!
WARNING:__main__:Sheep!

Note that (unless overridden) logs were only repeated after the sleep() call, and the repeated log also included an extra summary message added afterwards.

When we override rate-limiting above, you'll see our filter reads dynamic configs from logging's extra parameter.

Be very careful not to forget the extra= name part of the argument, as then the logging framework will assume you're passing arguments meant for formatting in the logging message and your options will silently be ignored!

Rate-limit only when specified

If you want most of your logs to be unaffected and you only have some you want to specifically rate-limit, then you can do the following:

import logging
from log_rate_limit import StreamRateLimitFilter, RateLimit
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Add our filter, but don't assign unique streams to logs by default
logger.addFilter(StreamRateLimitFilter(period_sec=1, all_unique=False))
# Normal logs are now not rate-limited
for i in range(3):
    logger.info(f"Status update: {i}")
# Only those we manually assign a stream will be rate-limited
for _ in range(3):
    logger.warning("Issue!", extra=RateLimit(stream_id="issue"))

Which only outputs the following:

INFO:__main__:Status update: 0
INFO:__main__:Status update: 1
INFO:__main__:Status update: 2
WARNING:__main__:Issue!

Dynamically override configuration options

Some options set during creation of the initial filter can be overridden for individual log calls. This is done by adding the extra parameter to any specific log call, e.g.:

# Override the rate limit for this specific log call
logger.warning("Test1", extra=RateLimit(stream_id="stream1", period_sec=30))
# Override the allow_next_n value for a set of logs in the same stream so that this group of logs don't restrict one
# another from occuring consecutively
logger.warning("Test", extra=RateLimit(stream_id="stream2", allow_next_n=2))
logger.info("Extra", extra=RateLimit(stream_id="stream2"))
logger.debug("Info", extra=RateLimit(stream_id="stream2"))

If you want to set custom options for a large group of log calls without repeatedly adding the extra parameter, it's possible to use a LoggerAdapter:

import logging
from log_rate_limit import StreamRateLimitFilter, RateLimit

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Add our filter
logger.addFilter(StreamRateLimitFilter(period_sec=1))

# Use LoggerAdapter to assign additional "extra" parameters to all calls using this logger
global_extra = RateLimit(stream_id="custom_stream", period_sec=20)
logger = logging.LoggerAdapter(logger, global_extra)
# Log many warnings
for _ in range(100):
    logger.warning("Wolf!")
for i in range(100):
    logger.warning("No really, a wolf!")

Which merely outputs:

WARNING:__main__:Wolf!

Since both log calls are in the same stream.

Alternatively (to a LoggerAdapter), custom options can also be added by writing your own logging.Filter.

Dynamic stream ID

To ensure that the same log line doesn't rate limit with itself when it's messages actually have different content, a dynamic stream ID can be assigned based on the message content. For example:

logger.warning(f"Error occured on device {device_id}!", extra=RateLimit(stream_id=f"error_on_{device_id}"))

Installation

Install from PyPI

With Python 3 installed on your system, you can run:

pip install log-rate-limit

To test that installation worked, you can run:

python -c "import log_rate_limit"

and you can uninstall at any time with:

pip uninstall log-rate-limit

To install with poetry:

poetry add log-rate-limit

Install from Github

To install the newest code directly from Github:

pip install git+https://github.com/samuller/log-rate-limit

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

log_rate_limit-1.1.0.tar.gz (12.0 kB view details)

Uploaded Source

Built Distribution

log_rate_limit-1.1.0-py3-none-any.whl (11.9 kB view details)

Uploaded Python 3

File details

Details for the file log_rate_limit-1.1.0.tar.gz.

File metadata

  • Download URL: log_rate_limit-1.1.0.tar.gz
  • Upload date:
  • Size: 12.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.2.2 CPython/3.8.10 Linux/5.10.16.3-microsoft-standard-WSL2

File hashes

Hashes for log_rate_limit-1.1.0.tar.gz
Algorithm Hash digest
SHA256 4ac93b0d8c4ee249159201487992de24c72abcb1e02b4ec52f90a2dbb4ae3eba
MD5 4e4361c22ed71a40ab32b65e74fe6ff7
BLAKE2b-256 d8dd152e5d367703bd5ef0daf18e277c1dd7f2fe60f0d206217c8313b1efa211

See more details on using hashes here.

File details

Details for the file log_rate_limit-1.1.0-py3-none-any.whl.

File metadata

  • Download URL: log_rate_limit-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 11.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.2.2 CPython/3.8.10 Linux/5.10.16.3-microsoft-standard-WSL2

File hashes

Hashes for log_rate_limit-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e614d11defb06929a4be1ff0551f9a0a0f36eef5878ed58d7c3119c869727428
MD5 88011b099fae590ecb486a7bc801694a
BLAKE2b-256 e62306e8b135e32b65e81f68ddaf7695f5ef798fc49ac0fc599062da905ad6e9

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page