|
| 1 | +""" |
| 2 | + EJERCICIO: |
| 3 | + Explora el concepto de "logging" en tu lenguaje. Configúralo y muestra |
| 4 | + un ejemplo con cada nivel de "severidad" disponible. |
| 5 | +
|
| 6 | + DIFICULTAD EXTRA (opcional): |
| 7 | + Crea un programa ficticio de gestión de tareas que permita añadir, eliminar |
| 8 | + y listar dichas tareas. |
| 9 | + - Añadir: recibe nombre y descripción. |
| 10 | + - Eliminar: por nombre de la tarea. |
| 11 | + Implementa diferentes mensajes de log que muestren información según la |
| 12 | + tarea ejecutada (a tu elección). |
| 13 | + Utiliza el log para visualizar el tiempo de ejecución de cada tarea. |
| 14 | +""" |
| 15 | +import logging |
| 16 | +from os import remove |
| 17 | +from time import sleep |
| 18 | + |
| 19 | +print(f"{'#' * 47}") |
| 20 | +print(f"## Explicación {'#' * 30}") |
| 21 | +print(f"{'#' * 47}") |
| 22 | + |
| 23 | +print(r""" |
| 24 | +https://docs.python.org/es/3/howto/logging.html <= en este link se haya una muy buena explicación de qué es y cuándo se usa "logging". |
| 25 | +
|
| 26 | +----------------------------------------------------------------------------------------------------------------------------- |
| 27 | +
|
| 28 | +Ejemplo de logging "sencillo": |
| 29 | +
|
| 30 | + logger = logging.getLogger("reto_25_neslarra") |
| 31 | + logging.basicConfig(filename=logger.name + '.log', encoding='utf-8', filemode='a', |
| 32 | + format='%(asctime)s - %(levelname)s: %(message)s', level=logging.DEBUG, |
| 33 | + datefmt='%Y-%b-%d %H:%M:%S') |
| 34 | + |
| 35 | + logger.debug('This message should go to the log file') |
| 36 | + logger.info('So should this') |
| 37 | + logger.warning('And this, too') |
| 38 | + logger.error('And non-ASCII stuff, too, like Øresund and Malmö') |
| 39 | + logger.critical('Oopsie doopsie!!!') |
| 40 | +
|
| 41 | +----------------------------------------------------------------------------------------------------------------------------- |
| 42 | +
|
| 43 | +Ejemplo de logging desviando, formateando y filtrando eventos: |
| 44 | +
|
| 45 | + def filter_console(reg): |
| 46 | + if reg.levelname in ("INFO", "DEBUG"): |
| 47 | + return True |
| 48 | + return False |
| 49 | + |
| 50 | + |
| 51 | + def filter_logfile(reg): |
| 52 | + if reg.levelname in ("WARNING", "ERROR", "CRITICAL"): |
| 53 | + return True |
| 54 | + return False |
| 55 | + |
| 56 | + |
| 57 | + log_format = logging.Formatter('%(asctime)s - %(levelname)s %(funcName)s (%(lineno)d) %(message)s', datefmt='%Y-%b-%d %H:%M:%S') |
| 58 | + logFile = 'reto_25_neslarra.log' |
| 59 | + |
| 60 | + file_handler = logging.FileHandler(logFile, encoding='utf-8') |
| 61 | + file_handler.setFormatter(log_format) |
| 62 | + file_handler.setLevel(logging.WARNING) |
| 63 | + # file_handler.addFilter(filter_logfile) # NO hace falta filtrar pque el level ya sólo toma WARNING, ERROR y CRITICAL <= SOLO EJEMPLO |
| 64 | + |
| 65 | + stream_handler = logging.StreamHandler() |
| 66 | + stream_handler.setFormatter(log_format) |
| 67 | + stream_handler.setLevel(logging.DEBUG) |
| 68 | + stream_handler.addFilter(filter_console) |
| 69 | + |
| 70 | + logger = logging.getLogger('root') |
| 71 | + logger.setLevel(logging.DEBUG) |
| 72 | + |
| 73 | + logger.addHandler(file_handler) |
| 74 | + logger.addHandler(stream_handler) |
| 75 | + |
| 76 | + logger.debug('Se muestra SÓLO por consola') |
| 77 | + logger.info('Se muestra SÓLO por consola') |
| 78 | + logger.warning('Se muestra SÓLO por fichero de log') |
| 79 | + logger.error('Se muestra SÓLO por fichero de log') |
| 80 | + logger.critical('Se muestra SÓLO por fichero de log') |
| 81 | + |
| 82 | + _ = input("Revisar el fichero de log => apretar cualquier tecla para borarrlo y salir.") |
| 83 | + logging.shutdown() |
| 84 | + remove(logFile) |
| 85 | +""") |
| 86 | + |
| 87 | +print(f"{'#' * 52}") |
| 88 | +print(f"## Dificultad Extra {'#' * 30}") |
| 89 | +print(f"{'#' * 52}\n") |
| 90 | + |
| 91 | + |
| 92 | +class Task: |
| 93 | + |
| 94 | + logger = logging.getLogger("root") |
| 95 | + log_file = "reto_25_" + logger.name + '.log' |
| 96 | + logging.basicConfig(filename=log_file, encoding='utf-8', filemode='a', |
| 97 | + format='%(asctime)s - %(levelname)s: %(message)s', level=logging.DEBUG, |
| 98 | + datefmt='%Y-%b-%d %H:%M:%S') |
| 99 | + |
| 100 | + def __init__(self, taskname: str): |
| 101 | + self.taskname = taskname |
| 102 | + Task.log_task(self.taskname) |
| 103 | + |
| 104 | + @classmethod |
| 105 | + def log_task(cls, taskname): |
| 106 | + cls.logger.info(taskname) |
| 107 | + |
| 108 | + @classmethod |
| 109 | + def log_shutdown(cls): |
| 110 | + logging.shutdown() |
| 111 | + remove(cls.log_file) |
| 112 | + |
| 113 | + |
| 114 | +task1 = Task("Salir de la cama") |
| 115 | +sleep(1) |
| 116 | +task2 = Task("Ventilar") |
| 117 | +sleep(1) |
| 118 | +task3 = Task("Ordenar la habitación") |
| 119 | +sleep(1) |
| 120 | +task4 = Task("Bañarme") |
| 121 | +sleep(1) |
| 122 | +task5 = Task("Vestirme") |
| 123 | +sleep(1) |
| 124 | +task6 = Task("Desayunar") |
| 125 | +sleep(1) |
| 126 | +task7 = Task("Ponerme a trabajar") |
| 127 | + |
| 128 | +_ = input("Revisar el fichero de log => apretar cualquier tecla para borarrlo y salir.") |
| 129 | +Task.log_shutdown() |
0 commit comments