summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorVinay Sajip <vinay_sajip@yahoo.co.uk>2010-10-25 13:57:39 (GMT)
committerVinay Sajip <vinay_sajip@yahoo.co.uk>2010-10-25 13:57:39 (GMT)
commita39c571061658967918276224a4992d1b421ae3f (patch)
treec567b97c3f4d3128dc1c4a00cfb0807513d00e42 /Lib
parent7e9065cf8c9d2465af002bfc13687d72e9a9dcdd (diff)
downloadcpython-a39c571061658967918276224a4992d1b421ae3f.zip
cpython-a39c571061658967918276224a4992d1b421ae3f.tar.gz
cpython-a39c571061658967918276224a4992d1b421ae3f.tar.bz2
logging: Added style option to Formatter to allow %, {} or himBHformatting.
Diffstat (limited to 'Lib')
-rw-r--r--Lib/logging/__init__.py39
-rw-r--r--Lib/test/test_logging.py48
2 files changed, 82 insertions, 5 deletions
diff --git a/Lib/logging/__init__.py b/Lib/logging/__init__.py
index 7f217d4..0e29cf3 100644
--- a/Lib/logging/__init__.py
+++ b/Lib/logging/__init__.py
@@ -395,18 +395,33 @@ class Formatter(object):
converter = time.localtime
- def __init__(self, fmt=None, datefmt=None):
+ def __init__(self, fmt=None, datefmt=None, style='%'):
"""
Initialize the formatter with specified format strings.
Initialize the formatter either with the specified format string, or a
default as described above. Allow for specialized date formatting with
the optional datefmt argument (if omitted, you get the ISO8601 format).
+
+ Use a style parameter of '%', '{' or '$' to specify that you want to
+ use one of %-formatting, :meth:`str.format` (``{}``) formatting or
+ :class:`string.Template` formatting in your format string.
+
+ .. versionchanged: 3.2
+ Added the ``style`` parameter.
"""
+ if style not in ('%', '$', '{'):
+ style = '%'
+ self._style = style
if fmt:
self._fmt = fmt
else:
- self._fmt = "%(message)s"
+ if style == '%':
+ self._fmt = "%(message)s"
+ elif style == '{':
+ self._fmt = '{message}'
+ else:
+ self._fmt = '${message}'
self.datefmt = datefmt
def formatTime(self, record, datefmt=None):
@@ -432,7 +447,7 @@ class Formatter(object):
s = time.strftime(datefmt, ct)
else:
t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
- s = "%s,%03d" % (t, record.msecs)
+ s = "%s,%03d" % (t, record.msecs) # the use of % here is internal
return s
def formatException(self, ei):
@@ -458,7 +473,14 @@ class Formatter(object):
"""
Check if the format uses the creation time of the record.
"""
- return self._fmt.find("%(asctime)") >= 0
+ if self._style == '%':
+ result = self._fmt.find("%(asctime)") >= 0
+ elif self._style == '$':
+ result = self._fmt.find("{asctime}") >= 0
+ else:
+ result = self._fmt.find("$asctime") >= 0 or \
+ self._fmt.find("${asctime}") >= 0
+ return result
def format(self, record):
"""
@@ -476,7 +498,14 @@ class Formatter(object):
record.message = record.getMessage()
if self.usesTime():
record.asctime = self.formatTime(record, self.datefmt)
- s = self._fmt % record.__dict__
+ style = self._style
+ if style == '%':
+ s = self._fmt % record.__dict__
+ elif style == '{':
+ s = self._fmt.format(**record.__dict__)
+ else:
+ from string import Template
+ s = Template(self._fmt).substitute(**record.__dict__)
if record.exc_info:
# Cache the traceback text to avoid converting it multiple times
# (it's constant anyway)
diff --git a/Lib/test/test_logging.py b/Lib/test/test_logging.py
index a738d7a..9aa6af3 100644
--- a/Lib/test/test_logging.py
+++ b/Lib/test/test_logging.py
@@ -1863,6 +1863,53 @@ class QueueHandlerTest(BaseTest):
self.assertEqual(data.name, self.que_logger.name)
self.assertEqual((data.msg, data.args), (msg, None))
+class FormatterTest(unittest.TestCase):
+ def setUp(self):
+ self.common = {
+ 'name': 'formatter.test',
+ 'level': logging.DEBUG,
+ 'pathname': os.path.join('path', 'to', 'dummy.ext'),
+ 'lineno': 42,
+ 'exc_info': None,
+ 'func': None,
+ 'msg': 'Message with %d %s',
+ 'args': (2, 'placeholders'),
+ }
+ self.variants = {
+ }
+
+ def get_record(self, name=None):
+ result = dict(self.common)
+ if name is not None:
+ result.update(self.variants[name])
+ return logging.makeLogRecord(result)
+
+ def test_percent(self):
+ "Test %-formatting"
+ r = self.get_record()
+ f = logging.Formatter('${%(message)s}')
+ self.assertEqual(f.format(r), '${Message with 2 placeholders}')
+ f = logging.Formatter('%(random)s')
+ self.assertRaises(KeyError, f.format, r)
+
+ def test_braces(self):
+ "Test {}-formatting"
+ r = self.get_record()
+ f = logging.Formatter('$%{message}%$', style='{')
+ self.assertEqual(f.format(r), '$%Message with 2 placeholders%$')
+ f = logging.Formatter('{random}', style='{')
+ self.assertRaises(KeyError, f.format, r)
+
+ def test_dollars(self):
+ "Test $-formatting"
+ r = self.get_record()
+ f = logging.Formatter('$message', style='$')
+ self.assertEqual(f.format(r), 'Message with 2 placeholders')
+ f = logging.Formatter('$$%${message}%$$', style='$')
+ self.assertEqual(f.format(r), '$%Message with 2 placeholders%$')
+ f = logging.Formatter('${random}', style='$')
+ self.assertRaises(KeyError, f.format, r)
+
class BaseFileTest(BaseTest):
"Base class for handler tests that write log files"
@@ -1945,6 +1992,7 @@ def test_main():
CustomLevelsAndFiltersTest, MemoryHandlerTest,
ConfigFileTest, SocketHandlerTest, MemoryTest,
EncodingTest, WarningsTest, ConfigDictTest, ManagerTest,
+ FormatterTest,
LogRecordClassTest, ChildLoggerTest, QueueHandlerTest,
RotatingFileHandlerTest,
#TimedRotatingFileHandlerTest