1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License.
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 #=============================================================================
23 # Author : Guillaume Boulant (CSSI)
24 # Rewritten by Renaud Barate (EDF R&D)
26 # Copyright : EDF 2001-2009
28 #=============================================================================
30 This module defines a class which provides logging facility in Salome:
36 from salome.kernel.deprecation import deprecated
37 from salome.kernel import termcolor
38 import salome.kernel.logconfig
40 class Logger(logging.Logger):
42 This class formats and displays log messages in Salome environment. It
43 inherits :class:`Logger<logging.Logger>` class defined in :mod:`logging`
44 module from Python library, so all methods from :class:`logging.Logger`
45 can be used here. The format of the traces is:
47 LEVEL [keyword] : Message
49 where `LEVEL` is the level of the message (`DEBUG`, `INFO`, etc.),
50 `keyword` is the name of the logger, and `Message` is the message to log.
52 When creating a new Logger object, the parameter `keyword` defines the
53 name of the logger, `level` defines the logging level (default is
54 :const:`logging.DEBUG` if KERNEL module is configured with --enable-debug
55 option or :const:`logging.WARNING` otherwise), and `color` defines the color
56 of the log messages for this logger (log messages will appear in color
57 only when displayed on color-capable ASCII terminals). See module
58 :mod:`salome.kernel.termcolor` for the color constants.
60 By default, log messages will be displayed only on standard output. They
61 can also be recorded in a file (see method :meth:`setLogFile`). For now,
62 the CORBA-based logging facility can not be used through this class.
64 A source filename `sourceFileName` can be defined. If this argument is
65 specified, then the `keyword` is modified to the basename of the `sourceFileName`
69 from salome.kernel.logger import Logger
71 log.debug("Debug message")
72 log.info("Information message")
73 log.warning("Warning message")
74 log.error("Error message")
75 log.critical("Fatal error message")
79 def __init__(self, keyword = "KEY", level = salome.kernel.logconfig.loggingLevel,
80 color = None, sourceFileName=None):
82 if sourceFileName is not None:
83 keyword = os.path.basename(sourceFileName).split('.')[0]
84 logging.Logger.__init__(self, keyword, level)
85 self._baseFormatString = "%(levelname)-8s [%(name)s] : %(message)s"
86 self._baseFormatter = logging.Formatter(self._baseFormatString)
87 if hasattr(sys.stdout, "flush"):
88 self._stdoutStream = sys.stdout
90 self._stdoutStream = _UnFlushableLogStream(sys.stdout)
91 self._stdoutHandler = logging.StreamHandler(self._stdoutStream)
92 self._stdoutHandler.setLevel(logging.DEBUG)
94 self.addHandler(self._stdoutHandler)
95 self._fileHandler = None
99 Log all messages, including DEBUG level messages (equivalent to
100 ``setLevel(logging.DEBUG)``).
102 self.setLevel(logging.DEBUG)
104 def setLogFile(self, logFilename):
106 Define a log file to record the log messages (in addition to the
110 self._fileHandler = logging.FileHandler(logFilename, 'w')
111 self._fileHandler.setLevel(logging.DEBUG)
112 self._fileHandler.setFormatter(self._baseFormatter)
113 self.addHandler(self._fileHandler)
115 def setColor(self, color):
117 Set the color of log messages on color-capable terminals. If `color`
118 is :const:`None`, the default color will be used.
120 if color is None or not termcolor.canDisplayColor(self._stdoutStream):
121 stdoutFormatter = self._baseFormatter
124 (termcolor.getControlSequence(color),
125 self._baseFormatString,
126 termcolor.getControlSequence(termcolor.DEFAULT)))
127 stdoutFormatter = logging.Formatter(format)
128 self._stdoutHandler.setFormatter(stdoutFormatter)
130 def closeLogFile(self):
131 """Close the log file."""
132 if self._fileHandler is not None:
133 self.removeHandler(self._fileHandler)
134 self._fileHandler.close()
135 self._fileHandler = None
139 Hide DEBUG level messages (equivalent to ``setLevel(logging.INFO)``).
141 self.setLevel(logging.INFO)
143 @deprecated("Deprecated since version 5.1.5. Please replace with "
144 "Logger.critical(message)")
145 def fatal(self, message):
147 Log a message with CRITICAL level. This method only exists for
148 backward compatibility and is equivalent to ``critical(message)``.
150 self.critical(message)
153 class _UnFlushableLogStream:
155 This utility class allows to log messages to a stream with no `flush`
156 method. This is useful to send log messages to `PyOut` objects.
159 def __init__(self, stream):
160 self._stream = stream
162 def write(self, msg):
163 self._stream.write(msg)
169 class ExtLogger(Logger):
171 This class extends :class:`Logger` class and adds exception information
172 when DEBUG messages are recorded. It exists mainly for backward
173 compatibility, as the same thing can be done by calling
174 ``Logger.debug(message, exc_info = True)``.
177 @deprecated("Class ExtLogger is deprecated since version 5.1.5. See "
178 "documentation for replacement.")
179 def __init__(self, keyword = "KEY",
180 level = salome.kernel.logconfig.loggingLevel,
181 color = None, sourceFileName=None):
182 Logger.__init__(self, keyword, level, color, sourceFileName)
184 def debug( self, message ):
186 Log a DEBUG message with exception information (equivalent to
187 ``Logger.debug(message, exc_info = True)``).
189 Logger.debug(self, message, exc_info = True)
193 """Test function for logger module"""
197 log.info("Information message")
198 log.debug("Debug message")
199 log.fatal("Fatal error message")
203 log.info("This message displays data = " + str(data))
206 data["KERNEL"] = "V1"
208 log.info("This message displays data = " + str(data))
210 # Test with a non-string parameter
213 # Test with a default instance
215 log.info("Default logger")
217 # Test showDebug method
218 log.setLogFile("test.log")
219 log.debug("Debug trace")
221 log.debug("This trace should NOT be displayed")
223 log.debug("This trace should be displayed")
225 log.info("After closing the log file")
228 # Main function only used to test the module
229 if __name__ == "__main__":