Skip to content

Commit

Permalink
Use datetime by default to format log time
Browse files Browse the repository at this point in the history
Change logging time formatting to allow using datetime.strftime and
change the default converter to create a datetime that can contain more
information than the time tuple of the default converter. This allows
for having `datefmt` template strings that can use microseconds as part
of it.
  • Loading branch information
mariocj89 committed May 31, 2019
1 parent eea47e0 commit 5047d73
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
14 changes: 11 additions & 3 deletions Lib/logging/__init__.py
Expand Up @@ -25,6 +25,7 @@

import sys, os, time, io, re, traceback, warnings, weakref, collections.abc

import datetime
from string import Template
from string import Formatter as StrFormatter

Expand Down Expand Up @@ -550,7 +551,7 @@ class Formatter(object):
the record is emitted
"""

converter = time.localtime
converter = datetime.datetime.fromtimestamp

def __init__(self, fmt=None, datefmt=None, style='%', validate=True):
"""
Expand Down Expand Up @@ -600,10 +601,17 @@ def formatTime(self, record, datefmt=None):
set the 'converter' attribute in the Formatter class.
"""
ct = self.converter(record.created)

try:
formatting_function = ct.strftime
except AttributeError:
def formatting_function(format):
return time.strftime(format, ct)

if datefmt:
s = time.strftime(datefmt, ct)
s = formatting_function(datefmt)
else:
t = time.strftime(self.default_time_format, ct)
t = formatting_function(self.default_time_format)
s = self.default_msec_format % (t, record.msecs)
return s

Expand Down
15 changes: 15 additions & 0 deletions Lib/test/test_logging.py
Expand Up @@ -3893,6 +3893,21 @@ def test_time(self):
f.format(r)
self.assertEqual(r.asctime, '1993-04-21 08:03:00,123')

def test_time_datetime_or_time_tiple_format_are_identical(self):
r = self.get_record()
f1 = logging.Formatter('%(asctime)s')
f1.converter = datetime.datetime.fromtimestamp
f2 = logging.Formatter('%(asctime)s')
f2.converter = time.localtime
assert f1.format(r) == f2.format(r)

def test_time_formatting_of_microsecond(self):
r = self.get_record()
f = logging.Formatter('%(asctime)s', datefmt="%f")
created_microseconds = int(r.created % 1 * 10 ** 6)
self.assertEquals(int(f.format(r)), created_microseconds)


class TestBufferingFormatter(logging.BufferingFormatter):
def formatHeader(self, records):
return '[(%d)' % len(records)
Expand Down

0 comments on commit 5047d73

Please sign in to comment.