Librería logging (Utilidad para registro)#
Última modificación: Mayo 14, 2022
Cuándo usar logging?#
print(): para impresión normal.
logging.info(): para reportar eventos durante la operación normal del programa.
logging.debug(): para reportar información detallada de depuración durante la operación normal del programa.
logging.warn(): si la aplicación cliente puede manejar la situaación.
logging.warning(): si la aplicación cliente no puede manejar la situación y el evento debe registrarse.
logging.error(), logging.exception(), logging.critical(): para reportar la supresión de un error sin generar una excepción.
Niveles#
DEBUG
: Información detallada.INFO
: Confirmación de que las cosas están trabajando como es esperado.WARNING
: Indicación de que algo inexperado está pasando (Nivel por defecto).ERROR
: Error serio, indicando que el software no es capaz de ejecuar alguna función.CRITICAL
: Error serio, indicando que el software no se puede seguir ejecutando.
[1]:
import logging
logging.warning("Watch out!") # will print a message to the console
logging.info("I told you so") # will not print anything
WARNING:root:Watch out!
Logging a un archivo#
[2]:
%%writefile demo.py
import logging
logging.basicConfig(filename="./example.log", 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ö")
Overwriting demo.py
[3]:
!python3 demo.py
[4]:
!cat example.log
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: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ö
Logging desde un módulo#
[5]:
%%writefile 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()
Overwriting myapp.py
[6]:
%%writefile mylib.py
import logging
def do_something():
logging.info('Doing something')
Overwriting mylib.py
[7]:
!python3 myapp.py
[8]:
!cat ./myapp.log
INFO:root:Started
INFO:root:Doing something
INFO:root:Finished
INFO:root:Started
INFO:root:Doing something
INFO:root:Finished
Logging data#
[9]:
import logging
logging.warning('%s before you %s', 'Look', 'leap!')
WARNING:root:Look before you leap!
Formato de los mensajes#
[10]:
%%python3
import logging
log_format = '%(levelname)s:%(message)s'
logging.basicConfig(format=log_format, level=logging.DEBUG)
logging.debug("This message should appear on the console")
logging.info("So should this")
logging.warning("And this, too")
DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too
Fecha y hora en mensajes#
[11]:
%%python3
import logging
logging.basicConfig(format='%(asctime)s %(message)s')
logging.warning('is when this event was logged.')
2022-04-20 03:11:50,183 is when this event was logged.
[12]:
%%python3
import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')
04/20/2022 03:11:50 AM is when this event was logged.
Logging flow#
Loggers#
Los objetos logger tienen tres funciones:
Exponer verios métodos al código de la aplicación tal que ella pueda generar mensajes en ejecución.
Determina las acciones de acuerdo con la severidad del mensaje.
Pasa mensajes a todos los manejadores relevantes.
Métodos de configuración de los loggers#
Logger.setLevel(): especifica la severidad mínima a manejar por el logger
Logger.addHandler() / Logger.removeHandler(): adicionan y remueven manejadores.
Logger.addFilter() / Logger.removeFilter(): adicionan y remueven filtros.
Métodos para crear mensajes log#
Logger.debug()
Logger.info()
Logger.warning()
Logger.error()
Logger.critical()
Logger.exception()
Logger.log()
Handlers#
Responsables de despachar los mensajes de log apropiados a una destinación específica.
Métodos de configuración de los handlers.#
setLevel()
setFormater()
addFilter() / removeFilter()
Formatters#
logging.Formatter.__init__(fmt=None, datefmt=None, style='%')
'%(asctime)s - %(levelname)s - %(message)s'
Configuración - ejemplo 1#
[13]:
%%writefile simple_logging_module.py
import logging
# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
Overwriting simple_logging_module.py
[14]:
!python3 simple_logging_module.py
2022-04-20 03:11:50,458 - simple_example - DEBUG - debug message
2022-04-20 03:11:50,458 - simple_example - INFO - info message
2022-04-20 03:11:50,458 - simple_example - WARNING - warn message
2022-04-20 03:11:50,458 - simple_example - ERROR - error message
2022-04-20 03:11:50,458 - simple_example - CRITICAL - critical message
Configuración - ejemplo 2#
[15]:
%%writefile logging.conf
[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
Overwriting logging.conf
[16]:
%%writefile simple_logging_config.py
import logging
import logging.config
logging.config.fileConfig('logging.conf')
# create logger
logger = logging.getLogger('simpleExample')
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
Overwriting simple_logging_config.py
[17]:
!python3 simple_logging_config.py
2022-04-20 03:11:50,833 - simpleExample - DEBUG - debug message
2022-04-20 03:11:50,833 - simpleExample - INFO - info message
2022-04-20 03:11:50,833 - simpleExample - WARNING - warn message
2022-04-20 03:11:50,833 - simpleExample - ERROR - error message
2022-04-20 03:11:50,833 - simpleExample - CRITICAL - critical message
[18]:
!rm *.py *.log *.conf