Log bill exploded after a debug level was left on: per-logger levels and sampling
Cloud Logging ingestion jumped sixteen-fold because an incident-time LOG_LEVEL=DEBUG set the Python root logger, which quietly enabled SQLAlchemy and urllib3 debug output. Per-logger levels, sampling and an exclusion filter fixed the bill.
The monthly budget alert for our production project fired on the 9th instead of the 30th. The billing report showed one line item responsible: Cloud Logging ingestion. Daily ingested volume had gone from about 38 GiB to 610 GiB, and it had been that way for nineteen days. Nobody had shipped a logging change in that window.
A sample of the noisiest log stream from the orders-api pods looked like this:
{"severity":"DEBUG","logger":"urllib3.connectionpool","message":"https://oauth2.googleapis.com:443 \"POST /token HTTP/1.1\" 200 None"}
{"severity":"INFO","logger":"sqlalchemy.engine.Engine","message":"SELECT orders.id, orders.status, orders.customer_email ... WHERE orders.id = %(id_1)s"}
{"severity":"DEBUG","logger":"sqlalchemy.engine.Engine","message":"Row (8812, 'paid', 'buyer@example.com', ...)"}
{"severity":"INFO","logger":"uvicorn.access","message":"10.8.2.14:51544 - \"GET /healthz HTTP/1.1\" 200"}
The last line is noise we always had. The first three were new, and the third one contained customer email addresses, which turned a cost problem into a data-handling problem.
Finding the source of the volume
The ingestion metric logging.googleapis.com/billing/bytes_ingested in Cloud Monitoring, grouped by resource, pointed at the k8s_container resource in the orders namespace. To see which loggers produced it, we pulled a ten-minute sample and counted by logger name:
gcloud logging read \
'resource.type="k8s_container" AND resource.labels.namespace_name="orders"
AND timestamp>="2027-01-09T10:00:00Z" AND timestamp<"2027-01-09T10:10:00Z"' \
--format=json --limit=200000 \
| jq -r '.[] | .jsonPayload.logger // "none"' | sort | uniq -c | sort -rn | head
118204 sqlalchemy.engine.Engine
31877 urllib3.connectionpool
12410 google.auth.transport.requests
9120 uvicorn.access
2310 orders.api
Our own application logger was under two percent of the lines.
What we ruled out
A new feature logging too much. The deploy history for the window had only dependency bumps and one copy change. None touched logging.
SQLAlchemy
echo=True. We grepped for it; the engine was created withecho=False.A logging agent misconfiguration duplicating lines. Each line appeared once, with one
insertId.
Root cause
During an incident nineteen days earlier, an engineer set LOG_LEVEL=DEBUG in the service ConfigMap to get more detail. Our startup code applied that value to the root logger:
logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO"), handlers=[json_handler])
Library loggers such as sqlalchemy.engine, urllib3 and google.auth do not set their own level, so their effective level is inherited from the root. At root DEBUG, SQLAlchemy logs every statement at INFO and every result row at DEBUG, regardless of echo=False. The incident was closed, the ConfigMap change was never reverted, and the pods kept the setting through every later rollout.
How Python logging levels inherit
Every logger has a level, and NOTSET (the default for libraries) means "ask my parent". The parent chain ends at the root logger. So one call to basicConfig(level=DEBUG) changes the effective level of every library logger that did not set its own. SQLAlchemy documents this directly: echo is a shortcut that configures the sqlalchemy.engine logger, and when the logger is enabled through normal logging configuration, statement and row output appears anyway.
Why the bill moved so much
Cloud Logging charges for data written into log buckets after a free monthly allotment per project. Logs written to the _Default bucket are billed by volume, so a few verbose libraries running on every request in twelve pods scale linearly with traffic. Excluded logs are not ingested and not charged, which matters for the fix.
Environment
Component | Version / value |
|---|---|
Platform | GKE Standard 1.31, Cloud Logging via the built-in logging agent |
Runtime | Python 3.12 |
Framework | FastAPI 0.115 on Uvicorn 0.32 |
ORM | SQLAlchemy 2.0 |
Pods | 12 replicas of |
Config |
|
Minimal reproduction
import logging
from sqlalchemy import create_engine, text
logging.basicConfig(level=logging.DEBUG)
engine = create_engine("sqlite://", echo=False)
with engine.connect() as conn:
conn.execute(text("select 1")).all()
# prints the SELECT at INFO and the row at DEBUG even though echo=False
Who is affected
Any Python service that sets the root logger level from a single variable, uses libraries that log at DEBUG or INFO, and ships stdout to a billed backend. The same pattern exists in Node (DEBUG=* enabling every debug-based module) and in Java when the root logger level is lowered in Logback or Log4j.
1. Per-logger levels instead of one root level
The root stays at WARNING. Our own loggers follow LOG_LEVEL. Known noisy libraries are pinned explicitly:
import logging.config, os
APP_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
logging.config.dictConfig({
"version": 1,
"disable_existing_loggers": False,
"formatters": {"json": {"()": "orders.logging.JsonFormatter"}},
"handlers": {"stdout": {"class": "logging.StreamHandler", "formatter": "json"}},
"root": {"level": "WARNING", "handlers": ["stdout"]},
"loggers": {
"orders": {"level": APP_LEVEL},
"sqlalchemy.engine": {"level": "WARNING"},
"urllib3": {"level": "WARNING"},
"google.auth": {"level": "WARNING"},
"uvicorn.access": {"level": "INFO", "filters": ["drop_health"]},
},
"filters": {"drop_health": {"()": "orders.logging.DropPaths", "paths": ["/healthz", "/readyz"]}},
})
class DropPaths(logging.Filter):
def __init__(self, paths):
super().__init__()
self.paths = tuple(paths)
def filter(self, record):
return not any(f" {p} " in record.getMessage() for p in self.paths)
If someone needs SQL output during an incident, they set LOG_LEVEL_SQLALCHEMY=INFO deliberately, which we read into the sqlalchemy.engine entry. Turning on our own debug output no longer turns on everyone else's.
2. Debug that expires on its own
We replaced the plain variable with an expiry:
until = os.environ.get("LOG_DEBUG_UNTIL") # e.g. 2027-01-09T14:00:00Z
if until and datetime.now(timezone.utc) < datetime.fromisoformat(until.replace("Z", "+00:00")):
APP_LEVEL = "DEBUG"
A forgotten value stops working after a few hours, and a startup warning prints the expiry so it shows up in the logs it affects.
3. Sample the high-volume, low-value lines
Successful request logs are useful in aggregate, not individually. We keep every warning and error and ten percent of successful completions:
class SampleInfo(logging.Filter):
def __init__(self, rate=0.1):
super().__init__()
self.rate = rate
def filter(self, record):
if record.levelno >= logging.WARNING:
return True
if getattr(record, "event", "") != "http.request.completed":
return True
return random.random() < self.rate
We add sample_rate=0.1 to sampled lines so counts can be multiplied back in queries, and we rely on metrics, not log counts, for request rates.
4. A backstop at the platform
Code fixes protect one service. A sink exclusion on the _Default sink protects the project from the next service that makes the same mistake:
gcloud logging sinks update _Default \
--add-exclusion=name=drop-k8s-debug,filter='resource.type="k8s_container" AND severity<=DEBUG'
Excluded entries are dropped before ingestion. The trade-off is that they are gone; if you need debug output during an incident, remove the exclusion for that window. Teams running an OpenTelemetry Collector can do the same at the agent with the filter processor and a condition such as severity_number < SEVERITY_NUMBER_INFO.
Alternatives and trade-offs
Route verbose logs to a cheaper bucket with short retention instead of dropping them. Useful if auditors want them kept.
Lower retention does not help here: the charge is for ingestion, not storage time.
Turning off the platform agent removes the problem and also removes every log you need.
How to test the fix
A unit test locks the effective levels so a refactor cannot bring the root-level pattern back:
def test_library_loggers_stay_quiet(monkeypatch):
monkeypatch.setenv("LOG_LEVEL", "DEBUG")
configure_logging()
assert logging.getLogger("orders.api").getEffectiveLevel() == logging.DEBUG
for name in ("sqlalchemy.engine", "urllib3", "google.auth"):
assert logging.getLogger(name).getEffectiveLevel() >= logging.WARNING
pytest tests/test_logging_config.py -q
Confirming in production
After the rollout, the logger breakdown for the same ten-minute window showed orders.api as the largest source and SQLAlchemy at zero. Daily ingestion settled at about 24 GiB, lower than before the incident because health-check lines and successful request lines were now filtered and sampled. The bytes_ingested chart is pinned on the service dashboard.
Regression guard
An alerting policy on
logging.googleapis.com/billing/bytes_ingestedfires when a namespace's hourly volume exceeds three times its seven-day average.The unit test above runs in CI.
A rule script fails CI on any
basicConfig(level=orgetLogger().setLevel(call outside the logging module.
Security implications
The bug wrote customer email addresses and order rows into logs for nineteen days, so we treated it as a data exposure. Cloud Logging cannot delete single entries, so we narrowed access to the _Default bucket to the on-call group, confirmed no export sink had copied the entries elsewhere, let them age out under the bucket's 30-day retention and recorded the exposure in our incident log. Lesson recorded: verbose library logging is a privacy risk, not only a cost risk. The fix reduces surface; the exclusion filter must not be the only control, because errors at WARNING or above still pass through it.
Prevention checklist
Never set the root logger from an application level variable; configure loggers by name.
Pin known noisy libraries to WARNING explicitly.
Make debug settings expire.
Sample high-volume success logs and keep every error.
Alert on ingestion bytes per namespace, not only on the monthly budget.
References
Python logging HOWTO, logger hierarchy: https://docs.python.org/3/howto/logging.html
SQLAlchemy engine logging: https://docs.sqlalchemy.org/en/20/core/engines.html#configuring-logging
Cloud Logging pricing: https://cloud.google.com/stackdriver/pricing
Cloud Logging exclusion filters: https://cloud.google.com/logging/docs/routing/overview#exclusions
OpenTelemetry Collector filter processor: https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/processor/filterprocessor
Add a label
Embed this post
<iframe src="https://hibug.me/log-bill-exploded-debug-level-sampling" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I moved into security from software development, and I still think like a developer: what does this mean for the code I am about to merge? Today I run security training and help engineering teams build safer systems without slowing them down. This series is the course I wish I had been given early in my career. It covers the fundamentals, from the CIA triad and networking basics to cryptography and access control, explained for developers with concrete examples and no fear-mongering. Every topic ends with something you can check or change in your own systems this week.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.