Logging - основные принципы

Теги: logging  python 

Основной материал - Logging HOWTO

Когда и какой способ логировапия использовать

Task you want to perform The best tool for the task
Display console output for ordinary usage of a command line script or program print()
Report events that occur during normal operation of a program (e.g. for status monitoring or fault investigation) logging.info() (or logging.debug() for very detailed output for diagnostic purposes)
Issue a warning regarding a particular runtime event warnings.warn() in library code if the issue is avoidable and the client application should be modified to eliminate the warning
  logging.warning() if there is nothing the client application can do about the situation, but the event should still be noted
Report an error regarding a particular runtime event Raise an exception
Report suppression of an error without raising an exception (e.g. error handler in a long-running server process) logging.error(), logging.exception() or logging.critical() as appropriate for the specific error and application domain

Стандартные уровни логирования

Level When it’s used
DEBUG Detailed information, typically of interest only when diagnosing problems.
INFO Confirmation that things are working as expected.
WARNING An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
ERROR Due to a more serious problem, the software has not been able to perform some function.
CRITICAL A serious error, indicating that the program itself may be unable to continue running.

The default level is WARNING.

A simple example

import logging
logging.warning('Watch out!')  # will print a message to the console
logging.info('I told you so')  # will not print anything

INFO не выведен, потому что дефолтный уровень логирования WARNING

Logging to a file

import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
logging.error('And non-ASCII stuff, too, like Øresund and Malmö')
DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too
ERROR:root:And non-ASCII stuff, too, like Øresund and Malmö

Все сообщения выведены в файл, т.к. уровень DEBUG

Logging from multiple modules

# myapp.py
import logging
import mylib

def main():
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    logging.info('Started')
    mylib.do_something()
    logging.info('Finished')

if __name__ == '__main__':
    main()
# mylib.py
import logging

def do_something():
    logging.info('Doing something')

Остальная часть раздела - лог переменных, дат и формат вывода. Смотри.

Advanced Logging Tutorial

Работа с loggers, handlers, formaters