Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit eb14dec

Browse files
committed
Added example to recently added cookbook entry.
1 parent 6f8e81a commit eb14dec

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

Doc/howto/logging-cookbook.rst

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1920,3 +1920,31 @@ something, you can make it more palatable if you use an alias such as ``M`` or
19201920
``_`` for the message (or perhaps ``__``, if you are using ``_`` for
19211921
localization).
19221922

1923+
Examples of this approach are given below. Firstly, formatting with
1924+
:meth:`str.format`::
1925+
1926+
>>> __ = BraceMessage
1927+
>>> print(__('Message with {0} {1}', 2, 'placeholders'))
1928+
Message with 2 placeholders
1929+
>>> class Point: pass
1930+
...
1931+
>>> p = Point()
1932+
>>> p.x = 0.5
1933+
>>> p.y = 0.5
1934+
>>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', point=p))
1935+
Message with coordinates: (0.50, 0.50)
1936+
1937+
Secondly, formatting with :class:`string.Template`::
1938+
1939+
>>> __ = DollarMessage
1940+
>>> print(__('Message with $num $what', num=2, what='placeholders'))
1941+
Message with 2 placeholders
1942+
>>>
1943+
1944+
One thing to note is that you pay no significant performance penalty with this
1945+
approach: the actual formatting happens not when you make the logging call, but
1946+
when (and if) the logged message is actually about to be output to a log by a
1947+
handler. So the only slightly unusual thing which might trip you up is that the
1948+
parentheses go around the format string and the arguments, not just the format
1949+
string. That’s because the __ notation is just syntax sugar for a constructor
1950+
call to one of the ``XXXMessage`` classes shown above.

0 commit comments

Comments
 (0)