brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python logging.basicConfig can read the log level from an environment variable

Python
~/tips/tip-python-logging-level-from-env

import logging, os

Switches a script between quiet and verbose logging with an environment variable.

I want to turn on debug output for one run without editing the script.

import logging, os

logging.basicConfig(
    level=os.environ.get("LOGLEVEL", "INFO").upper(),
    format="%(asctime)s %(levelname)s %(name)s: %(message)s")

Run LOGLEVEL=DEBUG python3 app.py to see debug messages and nothing changes for normal runs. basicConfig accepts the level as a string, and the format adds a timestamp and the logger name. It does nothing if the root logger already has handlers, unless you pass force=True (Python 3.8 and later). Call it once, early, in your entry point and not inside library modules. Keep the format string in one place so every module logs the same way.

Further reading: logging documentation

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link