python et les syslog ou log *************************** Syslog ====== pour windows ------------ https://sourceforge.net/projects/pywin32/ .. code-block:: python import win32evtlogutil win32evtlogutil.ReportEvent('NameAppli', 2, eventType=1, strings=['alert','coucou2']) win32evtlogutil.ReportEvent('NameAppli', 2, eventType=3, strings=['info','coucou2']) pour linux ---------- .. code-block:: python import syslog syslog.syslog('Processing started') if error: syslog.syslog(syslog.LOG_ERR, 'Processing started') ou avec plus d'option .. code-block:: python syslog.openlog(logopt=syslog.LOG_PID, facility=syslog.LOG_MAIL) syslog.syslog('E-mail processing initiated...') Priority levels (high to low): LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG. Facilities: LOG_KERN, LOG_USER, LOG_MAIL, LOG_DAEMON, LOG_AUTH, LOG_LPR, LOG_NEWS, LOG_UUCP, LOG_CRON and LOG_LOCAL0 to LOG_LOCAL7. Log options: LOG_PID, LOG_CONS, LOG_NDELAY, LOG_NOWAIT and LOG_PERROR if defined in <syslog.h>. log fichier =========== .. code-block:: python import os, platform import logging if platform.platform().startswith('Windows'): logging_file = os.path.join(os.getenv('HOMEDRIVE'), os.getenv('HOMEPATH'), 'test.log') else: logging_file = os.path.join(os.getenv('HOME'), 'test.log') print("Logging to", logging_file) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s : %(levelname)s - %(name)s - %(module)s \ %(funcName)s : %(message)s', filename = logging_file, filemode = 'w', ) logging.debug("Start of the program") logging.info("Doing something") logging.warning("Dying now") Il existe les niveaux DEBUG, INFO, WARNING, ERROR et CRITICAL (fonction debug(), info(), warning(), error() and critical() ) Il existe plusieurs méthodes pour se connecter aux loggers (il peut y en avoir plusieurs en même temps): fichier, console, réseau; la configuration du logger est utilisable dans un module mais sera propager sur les autres modules ou classes appelées. Il existe au niveau du formatage de nombreuses options (cf doc) On peut aussi ajouter des paramètres qui permettent d'avoir des logs tournantes .. code-block:: python import glob import logging import logging.handlers LOG_FILENAME = 'logging_rotatingfile_example.out' # Set up a specific logger with our desired output level my_logger = logging.getLogger('MyLogger') my_logger.setLevel(logging.DEBUG) # Add the log message handler to the logger handler = logging.handlers.RotatingFileHandler( LOG_FILENAME, maxBytes=20, backupCount=5) my_logger.addHandler(handler) ici on aura 5 fichiers tournant un autre exemple avec gestion du niveau de log souhaité .. code-block:: python 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.warn("warn message") logger.error("error message") logger.critical("critical message") .. code-block:: python LEVEL_DEBUG = {'DEBUG':logging.DEBUG, 'INFO' : logging.INFO, 'WARNING' : logging.WARNING, 'ERROR' : logging.ERROR, 'CRITICAL' : logging.CRITICAL} .. note:: il existe des handlers qui permettent d'envoyer les messages à travers le réseau a un même logger on peut attacher plusieurs handler (une sortie console + une sortie fichier, ...)