4 # Copyright (C) 2010-2018 CEA/DEN
6 # This library is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation; either
9 # version 2.1 of the License.
11 # This library is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # Lesser General Public License for more details.
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with this library; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 see: http://sametmax.com/ecrire-des-logs-en-python
23 | # creation d'un formateur qui va ajouter le temps, le niveau
24 | # de chaque message quand on ecrira un message dans le log
25 | formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')
27 | # creation d'un handler qui va rediriger une ecriture du log vers
28 | # un fichier en mode 'append', avec 1 backup et une taille max de 1Mo
29 | file_handler = RotatingFileHandler('activity.log', 'a', 1000000, 1)
31 | # on lui met le niveau sur DEBUG, on lui dit qu'il doit utiliser le formateur
32 | # cree precedement et on ajoute ce handler au logger
33 | file_handler.setLevel(logging.DEBUG)
34 | file_handler.setFormatter(formatter)
35 | logger.addHandler(file_handler)
37 | # creation d'un second handler qui va rediriger chaque ecriture de log
39 | stream_handler = logging.StreamHandler()
40 | stream_handler.setLevel(logging.DEBUG)
41 | logger.addHandler(stream_handler)
43 | # Après 3 heures, on peut enfin logguer
44 | # Il est temps de spammer votre code avec des logs partout :
45 | logger.info('Hello')
46 | logger.warning('Testing %s', 'foo')
53 import logging as LOGI
54 from logging.handlers import BufferingHandler
56 import src.debug as DBG
60 _TRACE = LOGI.INFO - 2 # just below info
62 class LoggerSat(LOGI.Logger):
64 Elementary prototype for logger sat
65 add a level TRACE as log.trace(msg)
68 to assume store long log asci in files txt under/outside files xml
70 see: /usr/lib64/python2.7/logging/xxx__init__.py etc.
73 def __init__(self, name, level=LOGI.INFO):
75 Initialize the logger with a name and an optional level.
77 super(LoggerSat, self).__init__(name, level)
78 LOGI.addLevelName(_TRACE, "TRACE")
79 # LOGI.TRACE = _TRACE # only for coherency,
81 def trace(self, msg, *args, **kwargs):
83 Log 'msg % args' with severity '_TRACE'.
85 To pass exception information, use the keyword argument exc_info with
88 logger.trace("Houston, we have a %s", "long trace to follow")
90 if self.isEnabledFor(_TRACE):
91 self._log(_TRACE, msg, args, **kwargs)
93 class TestCase(unittest.TestCase):
96 initialLoggerClass = [] # to keep clean module logging
99 # one shot setUp() for this TestCase
100 self.initialLoggerClass.append(LOGI._loggerClass)
101 LOGI.setLoggerClass(LoggerSat)
104 # DBG.write("assert unittest", [a for a in dir(self) if "assert" in a])
108 # one shot tearDown() for this TestCase
111 LOGI.setLoggerClass(self.initialLoggerClass[0])
115 # LOGI.setLoggerClass(LoggerSat) # done once in test_000
117 lgr = LOGI.getLogger(name) # create it
118 lgr.setLevel("DEBUG")
119 self.assertEqual(lgr.__class__, LoggerSat)
120 self.assertEqual(lgr.name, name)
121 self.assertIn("trace", dir(lgr))
122 self.assertIn("TRACE", LOGI._levelNames.keys())
123 self.assertIn(_TRACE, LOGI._levelNames.keys())
124 self.assertEqual(LOGI.getLevelName(LOGI.INFO), "INFO")
125 self.assertEqual(LOGI.getLevelName(_TRACE), "TRACE")
127 # creation d'un handler pour chaque log sur la console
128 formatter = LOGI.Formatter('%(levelname)-8s :: %(message)s')
129 # stream_handler = LOGI.handlers.StreamHandler() # log outputs in console
130 stream_handler = LOGI.handlers.BufferingHandler(1000) # log outputs in memory
131 stream_handler.setLevel(LOGI.DEBUG)
132 stream_handler.setFormatter(formatter)
133 lgr.addHandler(stream_handler)
134 # print # skip one line if outputs in console
135 lgr.warning("!!! test warning")
136 lgr.info("!!! test info")
137 lgr.trace("!!! test trace")
138 lgr.debug("!!! test debug")
139 self.assertEqual(len(stream_handler.buffer), 4)
140 rec = stream_handler.buffer[-1]
141 self.assertEqual(rec.levelname, "DEBUG")
142 self.assertEqual(rec.msg, "!!! test debug")
143 self.assertEqual(stream_handler.get_name(), None) # what to serve ?
146 # LOGI.setLoggerClass(LoggerSat)
148 lgr = LOGI.getLogger(name) # find it as created yet in test_010
149 stream_handler = lgr.handlers[0]
150 rec = stream_handler.buffer[-1]
151 self.assertEqual(rec.levelname, "DEBUG")
152 self.assertEqual(rec.msg, "!!! test debug")
157 if __name__ == '__main__':
158 unittest.main(exit=False)