2. Logging

2.1. Korzystanie z logging

2.1.1. Poziomy logowania

  • Critical

  • Error

  • Warning

  • Info

  • Debug

import logging

logging.critical('Błąd krytyczny, kończę.')
logging.error('Błąd, ale kontynuuję.')
logging.warning('Uwaga będę coś robił')
logging.info('Będę coś robił')
logging.debug('Robię to tak')

2.1.2. Konfiguracja logowania

import logging

    format='"%(asctime).19s", "%(levelname)s", "%(message)s"'

log = logging.getLogger(__name__)

log.warning('warning!')  # zostanie zapisana do pliku
log.debug('wiadomosc debuggingowa')  # nie zostanie zapisana, bo level jest INFO, czyli powyżej DEBUG

2.1.3. Logowanie zdarzeń

import logging
log = logging.getLogger(__name__)

def sum(a, b):
    log.debug('Function `sum()` executed with: %s', locals())
    value = a + b
    log.debug(f'Will produce "{value}" as result')
    return value

sum(1, 2)
# Function `sum()` executed with: {'b': 2, 'a': 1}
# Will produce "3" as result
# 3

2.1.4. Wyciszanie logowania

import logging

    format='[%(asctime).19s] [%(levelname)s] %(message)s')

log = logging.getLogger(__name__)

log.debug('to jest moja debugowa wiadomosc')

2.2. Konfiguracja formatowania logów


convert table to CSV




The tuple of arguments merged into msg to produce message, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary). You shouldn't need to format this yourself.


Human-readable time when the LogRecord was created. By default this is of the form '2003-07-08 16:49:45,896' (the numbers after the comma are millisecond portion of the time).


Time when the LogRecord was created (as returned by time.time).


Exception tuple (à la sys.exc_info) or, if no exception has occurred, None. You shouldn't need to format this yourself.


Filename portion of pathname.


Name of function containing the logging call.


Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').


Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).


Source line number where the logging call was issued (if available).


Module (name portion of filename).


Millisecond portion of the time when the LogRecord was created.


The logged message, computed as msg % args. This is set when Formatter.format is invoked.


The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object (see arbitrary-object-messages). You shouldn't need to format this yourself.


Name of the logger used to log the call.


Full pathname of the source file where the logging call was issued (if available).


Process ID (if available).


Process name (if available).


Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.


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 record. You shouldn't need to format this yourself.


Thread ID (if available).


Thread name (if available).

2.2.1. DictConfig

    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
    'handlers': {
        'default': {
            'level': 'INFO',
            'formatter': 'standard',
            'class': 'logging.StreamHandler',
    'loggers': {
        '': {
            'handlers': ['default'],
            'level': 'INFO',
            'propagate': True
        'django.request': {
            'handlers': ['default'],
            'level': 'WARN',
            'propagate': False
Table 35. DictConfig




Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler


If filename is specified, open the file in this mode. Defaults to 'a'


Use the specified format string for the handler


Use the specified date/time format, as accepted by time.strftime()


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 '%'


Set the root logger level to the specified level


Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with filename - if both are present, a ValueError is raised


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

2.3. Rotate

  • logging.handlers.WatchedFileHandler

  • logging.handlers.RotatingFileHandler

  • logging.handlers.TimedRotatingFileHandler

from logging import handlers

handler = handlers.TimedRotatingFileHandler(filename, when=LOG_ROTATE)

handler.setFormatter(logging.Formatter(log_format, datefmt='%Y-%m-%d %H:%M:%S'))

#LOG_ROTATE = midnight
#set your log format