@@ -395,18 +395,33 @@ class Formatter(object):
395395
396396 converter = time .localtime
397397
398- def __init__ (self , fmt = None , datefmt = None ):
398+ def __init__ (self , fmt = None , datefmt = None , style = '%' ):
399399 """
400400 Initialize the formatter with specified format strings.
401401
402402 Initialize the formatter either with the specified format string, or a
403403 default as described above. Allow for specialized date formatting with
404404 the optional datefmt argument (if omitted, you get the ISO8601 format).
405+
406+ Use a style parameter of '%', '{' or '$' to specify that you want to
407+ use one of %-formatting, :meth:`str.format` (``{}``) formatting or
408+ :class:`string.Template` formatting in your format string.
409+
410+ .. versionchanged: 3.2
411+ Added the ``style`` parameter.
405412 """
413+ if style not in ('%' , '$' , '{' ):
414+ style = '%'
415+ self ._style = style
406416 if fmt :
407417 self ._fmt = fmt
408418 else :
409- self ._fmt = "%(message)s"
419+ if style == '%' :
420+ self ._fmt = "%(message)s"
421+ elif style == '{' :
422+ self ._fmt = '{message}'
423+ else :
424+ self ._fmt = '${message}'
410425 self .datefmt = datefmt
411426
412427 def formatTime (self , record , datefmt = None ):
@@ -432,7 +447,7 @@ def formatTime(self, record, datefmt=None):
432447 s = time .strftime (datefmt , ct )
433448 else :
434449 t = time .strftime ("%Y-%m-%d %H:%M:%S" , ct )
435- s = "%s,%03d" % (t , record .msecs )
450+ s = "%s,%03d" % (t , record .msecs ) # the use of % here is internal
436451 return s
437452
438453 def formatException (self , ei ):
@@ -458,7 +473,14 @@ def usesTime(self):
458473 """
459474 Check if the format uses the creation time of the record.
460475 """
461- return self ._fmt .find ("%(asctime)" ) >= 0
476+ if self ._style == '%' :
477+ result = self ._fmt .find ("%(asctime)" ) >= 0
478+ elif self ._style == '$' :
479+ result = self ._fmt .find ("{asctime}" ) >= 0
480+ else :
481+ result = self ._fmt .find ("$asctime" ) >= 0 or \
482+ self ._fmt .find ("${asctime}" ) >= 0
483+ return result
462484
463485 def format (self , record ):
464486 """
@@ -476,7 +498,14 @@ def format(self, record):
476498 record .message = record .getMessage ()
477499 if self .usesTime ():
478500 record .asctime = self .formatTime (record , self .datefmt )
479- s = self ._fmt % record .__dict__
501+ style = self ._style
502+ if style == '%' :
503+ s = self ._fmt % record .__dict__
504+ elif style == '{' :
505+ s = self ._fmt .format (** record .__dict__ )
506+ else :
507+ from string import Template
508+ s = Template (self ._fmt ).substitute (** record .__dict__ )
480509 if record .exc_info :
481510 # Cache the traceback text to avoid converting it multiple times
482511 # (it's constant anyway)
0 commit comments