18.4. Logging Config
filename- Specifies that aFileHandlerbe created, using the specified filename, rather than aStreamHandlerfilemode- If filename is specified, open the file in this mode. Defaults to'a'format- Use the specified format string for the handlerdatefmt- Use the specified date/time format, as accepted bytime.strftime()style- If format is specified, use this style for the format string. One of'%','{'or'$'for printf-style,str.format()orstring.Templaterespectively. Defaults to'%'level- Set the root logger level to the specified levelstream- Use the specified stream to initialize theStreamHandler. Note that this argument is incompatible withfilename- if both are present, aValueErroris raisedhandlers- If specified, this should be an iterable of already created handlers to add to the root logger. Any handlers which don't already have a formatter set will be assigned the default formatter created in this function. Note that this argument is incompatible withfilenameorstream- if both are present, aValueErroris raised
18.4.1. BasicConfig
logging.basicConfig(**kwargs)https://docs.python.org/3/library/logging.html#logging.basicConfig
>>> import logging
>>>
>>> logging.basicConfig(
... level='DEBUG',
... datefmt='%Y-%m-%d %H:%M:%S',
... format='{asctime} {levelname} {message}',
... style='{',
... filename='/tmp/myfile.log',
... filemode='w',
... )
18.4.2. DictConfig
logging.config.dictConfig(config)https://docs.python.org/3/library/logging.config.html#logging.config.dictConfig
https://docs.python.org/3/library/logging.config.html#dictionary-schema-details
Format- Descriptionfilename- Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandlerfilemode- If filename is specified, open the file in this mode. Defaults to 'a'format- Use the specified format string for the handlerdatefmt- Use the specified date/time format, as accepted by time.strftime()style- If format is specified, use this style for the format string. One of '%', '{' or '$' for printf-style, str.format() or string.Template respectively. Defaults to '%'level- Set the root logger level to the specified levelstream- Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with filename - if both are present, a ValueError is raisedhandlers- If specified, this should be an iterable of already created handlers to add to the root logger. Any handlers which don't already have a formatter set will be assigned the default formatter created in this function. Note that this argument is incompatible with filename or stream - if both are present, a ValueError is raised
{
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '{asctime} [{levelname}] {name}: {message}',
'style': '{',
},
},
'handlers': {
'default': {
'level': 'INFO',
'formatter': 'standard',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'': {
'handlers': ['default'],
'level': 'INFO',
'propagate': True
},
'django.request': {
'handlers': ['default'],
'level': 'WARN',
'propagate': False
},
}
}
18.4.3. Ini
logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=True, encoding=None)https://docs.python.org/3/library/logging.config.html#logging.config.fileConfig
[loggers]
keys=root,simpleExample
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
18.4.4. Yaml
version: 1
formatters:
simple:
format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: simple
stream: ext://sys.stdout
loggers:
simpleExample:
level: DEBUG
handlers: [console]
propagate: no
root:
level: DEBUG
handlers: [console]
18.4.5. Use Case - 0x01
File myapp/log.py
>>> import logging
>>>
>>>
>>> class LogFormatter(logging.Formatter):
... COLORS = {
... 'CRITICAL': '\033[91;1m',
... 'ERROR': '\033[91m',
... 'INFO': '\033[36m',
... 'WARNING': '\033[33m',
... 'DEBUG': '\033[32m',
... 'RESET': '\033[0m'
... }
...
... def format(self, record):
... message = super().format(record)
... reset = self.COLORS['RESET']
... color = self.COLORS[record.levelname]
... return f"{color}{message}{reset}"
File myapp/settings.py:
>>> import os
>>>
>>> LOGGING = {
... 'version': 1,
... 'disable_existing_loggers': False,
... 'formatters': {
... 'colored': {
... '()': 'myapp.mog.LogFormatter',
... 'format': "<{name}> [{levelname}] {message}",
... 'style': '{',
... },
... },
... 'handlers': {
... 'console': {
... 'level': 'DEBUG',
... 'class': 'logging.StreamHandler',
... 'formatter': 'colored',
... },
... },
... 'loggers': {
... 'django': {
... 'handlers': ['console'],
... 'level': os.getenv('MYAPP_LOG_LEVEL', default='DEBUG'),
... },
... 'django.db.backends': {
... 'handlers': ['console'],
... 'level': os.getenv('MYAPP_LOG_LEVEL', default='DEBUG'),
... },
... 'django.server': {
... 'handlers': ['console'],
... 'level': os.getenv('MYAPP_LOG_LEVEL', default='DEBUG'),
... },
... 'django.request': {
... 'handlers': ['console'],
... 'level': os.getenv('MYAPP_LOG_LEVEL', default='DEBUG'),
... },
... 'django.utils.security': {
... 'handlers': ['console'],
... 'level': os.getenv('MYAPP_LOG_LEVEL', default='DEBUG'),
... },
... 'django.utils.autoreload': {
... 'handlers': ['console'],
... 'level': 'ERROR',
... },
... },
... }
18.4.6. Further Reading
18.4.7. Assignments
# %% About
# - Name: Logging Config Level
# - Difficulty: easy
# - Lines: 1
# - Minutes: 1
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Change logging configuration to log DEBUG level messages
# 2. Use `logging` built-in module
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zmień konfigurację logowania, aby logować komunikaty na poziomie DEBUG
# 2. Use `logging` built-in module
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# %% Hints
# - `logging.basicConfig()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python has an is invalid version; expected: `3.10` or newer.'
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
import logging
# %% Types
# %% Data
# %% Result
# %% About
# - Name: Logging Config DateFmt
# - Difficulty: easy
# - Lines: 1
# - Minutes: 1
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Change logging date format to: "YYYY-MM-DD HH:MM:SS"
# 2. Use `logging` built-in module
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zmień format daty logowania na: "YYYY-MM-DD HH:MM:SS"
# 2. Use `logging` built-in module
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# %% Hints
# - `logging.basicConfig()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python has an is invalid version; expected: `3.10` or newer.'
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
import logging
# %% Types
# %% Data
# %% Result
# %% About
# - Name: Logging Config Filename
# - Difficulty: easy
# - Lines: 1
# - Minutes: 1
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Change logging output to file `FILE`
# 2. Use `logging` built-in module
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zmień wyjście logowania do pliku `FILE`
# 2. Use `logging` built-in module
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# %% Hints
# - `logging.basicConfig()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python has an is invalid version; expected: `3.10` or newer.'
>>> from pathlib import Path
>>> file = Path(FILE)
>>> file.unlink(missing_ok=True)
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
import logging
# %% Types
# %% Data
FILE = '_temporary.log'
# %% Result