18.3. Logging Formatters
SetUp:
>>> import logging
18.3.1. General
name- Name of the logger used to log the calllevelname- Text logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL)message- The logged message, computed asmsg % args. This is set whenFormatter.formatis invoked
>>> logging.basicConfig(format='%(levelname)s %(message)s')
>>>
>>> logging.critical('Error, cannot continue')
>>> logging.error('Error, can continue')
>>> logging.warning('Information, warn about something')
>>> logging.info('Information, inform about something')
>>> logging.debug('Debug, show detailed debugging information')
18.3.2. Dates
asctime- Human-readable time whenLogRecordwas created, example: 1969-07-21 02:56:15,123created- Time when theLogRecordwas created (as returned bytime.time)msecs- Millisecond portion of the time when theLogRecordwas created
>>> logging.basicConfig(format='%(asctime).19s %(message)s')
>>>
>>> logging.critical('Error, cannot continue')
>>> logging.error('Error, can continue')
>>> logging.warning('Information, warn about something')
>>> logging.info('Information, inform about something')
>>> logging.debug('Debug, show detailed debugging information')
18.3.3. File and Module
pathname- Full pathname of the source file where the logging call was issued (if available)filename- Filename portion ofpathnamemodule- Module (name portion offilename)funcName- Name of function containing the logging calllineno- Source line number where the logging call was issued (if available)
>>> logging.basicConfig(format='%(funcName)s:%(lineno)s %(message)s')
>>>
>>> logging.critical('Error, cannot continue')
>>> logging.error('Error, can continue')
>>> logging.warning('Information, warn about something')
>>> logging.info('Information, inform about something')
>>> logging.debug('Debug, show detailed debugging information')
18.3.4. Process and Thread
process- Process ID (if available)processName- Process name (if available)thread- Thread ID (if available)threadName- Thread name (if available)
18.3.5. Other
You shouldn't need to format this yourself
args- The tuple of arguments merged intomsgto producemessage, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary)exc_info- Exception tuple (à lasys.exc_info) if no exception has occurred,Nonemsg- The format string passed in the original logging call. Merged withargsto producemessage, or an arbitrary objectstack_info- Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this recordlevelno- Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL)relativeCreated- Time in milliseconds when theLogRecordwas created, relative to the time the logging module was loaded
18.3.6. Date Format
>>> import logging
>>>
>>>
>>> logging.basicConfig(
... format='%(asctime)s %(levelname)s %(message)s',
... datefmt='"%Y-%m-%d" "%H:%M:%S"',)
>>>
>>> logging.critical('Error, cannot continue')
>>> logging.error('Error, can continue')
>>> logging.warning('Information, warn about something')
>>> logging.info('Information, inform about something')
>>> logging.debug('Debug, show detailed debugging information')
18.3.7. Log Style
{- curly brackets; compare to f-string formatting%- percent sign; compare to formatting string with%$- dollar sign; compare to template vars from other languagesDefault mode is
%percent
% - percent sign (default):
>>> logging.basicConfig(
... format='%(asctime)s %(levelname)s %(message)s',
... style='%')
>>>
>>> logging.critical('Error, cannot continue')
>>> logging.error('Error, can continue')
>>> logging.warning('Information, warn about something')
>>> logging.info('Information, inform about something')
>>> logging.debug('Debug, show detailed debugging information')
{ - curly brackets:
>>> logging.basicConfig(
... format='{asctime} {levelname} {message}',
... style='{')
>>>
>>> logging.critical('Error, cannot continue')
>>> logging.error('Error, can continue')
>>> logging.warning('Information, warn about something')
>>> logging.info('Information, inform about something')
>>> logging.debug('Debug, show detailed debugging information')
$ - dollar sign:
>>> logging.basicConfig(
... format='$asctime $levelname $message',
... style='$')
>>>
>>> logging.critical('Error, cannot continue')
>>> logging.error('Error, can continue')
>>> logging.warning('Information, warn about something')
>>> logging.info('Information, inform about something')
>>> logging.debug('Debug, show detailed debugging information')
18.3.8. Use Case - 1
CSV log format
>>> import logging
>>>
>>>
>>> logging.basicConfig(
... level='DEBUG',
... datefmt='"%Y-%m-%d" "%H:%M:%S"',
... format='{asctime}, "{levelname}", "{message}"',
... style='{',
... filename='/tmp/myfile.csv')
>>>
>>> logging.critical('Error, cannot continue')
>>> logging.error('Error, can continue')
>>> logging.warning('Information, warn about something')
>>> logging.info('Information, inform about something')
>>> logging.debug('Debug, show detailed debugging information')
18.3.9. 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