Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

logging.basicConfig

Configures the root logger and its output handlers for simple applications.

Version: Python 3.14; repository image, production runtime not attested

Syntax

logging.basicConfig(**kwargs)

Configures the root logger and its output handlers for simple applications.

An existing root handler prevents ordinary reconfiguration. The explicit force option replaces previously attached root handlers.

level changes the root logger's threshold, and stream and format configure its handler. With existing root handlers the default call does nothing. force=True removes and closes those handlers before configuring new ones. If configuration proceeds, supplying both filename and stream raises ValueError. Only ready reaches the sample stream. Configure before using root shortcuts such as logging.warning, which can install a handler. A configured root ignores even filename plus stream without force. File output accepts encoding and errors to control unrepresentable characters.

import io,logging
a,b=io.StringIO(),io.StringIO()
logging.basicConfig(level=logging.INFO,stream=a,format='%(message)s',force=True)
logging.basicConfig(stream=b,level=logging.ERROR)
logging.info('one')
assert a.getvalue()=='one\n' and not b.getvalue()
logging.basicConfig(stream=b,format='%(message)s',level=logging.ERROR,force=True)
logging.info('hidden')
logging.error('two')
assert b.getvalue()=='two\n'
try: logging.basicConfig(stream=b,filename='unused',force=True)
except ValueError: pass
else: raise AssertionError
import tempfile,pathlib
logging.basicConfig(stream=b,force=True)
logging.basicConfig(filename='ignored',stream=b)
with tempfile.TemporaryDirectory() as d:
    path=pathlib.Path(d)/'ref.log'
    logging.basicConfig(filename=path,encoding='ascii',errors='replace',format='%(message)s',level=logging.INFO,force=True)
    logging.info('café')
    logging.basicConfig(stream=b,force=True)
    assert path.read_text(encoding='ascii')=='caf?\n'

Examples

import logging
from io import StringIO

out = StringIO()
logging.basicConfig(stream=out, level=logging.INFO, format="%(message)s", force=True)
logging.debug("hidden")
logging.info("ready")
print(out.getvalue().strip())

Result

ready

level changes the root logger's threshold, and stream and format configure its handler. With existing root handlers the default call does nothing. force=True removes and closes those handlers before configuring new ones. If configuration proceeds, supplying both filename and stream raises ValueError. Only ready reaches the sample stream. Configure before using root shortcuts such as logging.warning, which can install a handler. A configured root ignores even filename plus stream without force. File output accepts encoding and errors to control unrepresentable characters.

Sources