3

I am using the logging module from Python and I need to get information about the starting and ending time of different functions calls. For this, I am currently using

formatter = logging.Formatter('%(message)s %(asctime)s.%(msecs)03d %(levelname)s',
                              datefmt='%H:%M:%S')

Since the calls of a particular function do not last more than a few milliseconds, I would like to get a better precision and have more decimal digits. How can I do this?

I nice solution at: Python logging: use milliseconds in time format

wrong_path
  • 376
  • 1
  • 6
  • 18
  • If you're looking for a **working example down to nano-second precision**, I have posted one [here](https://stackoverflow.com/a/55612356/1672565). The answer below this question is not really helpful. – s-m-e Apr 10 '19 at 12:30

1 Answers1

4

For showing milliseconds:

logging.Formatter(fmt='%(asctime)s.%(msecs)03d',datefmt='%Y-%m-%d,%H:%M:%S')

An extensive example so you can compare:

def formatTime(self, record, datefmt=None):
    ct = self.converter(record.created)
    if datefmt:
        s = time.strftime(datefmt, ct)
    else:
        t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
        s = "%s,%03d" % (t, record.msecs)
    return s

Check this answer and also this doc to see all the milliseconds you can use:

import time

current_milli_time = lambda: int(round(time.time() * 1000))

Remember, 1000 milliseconds = 1 second, so you will be able to see 3 digits of milliseconds after the last second

lospejos
  • 1,976
  • 3
  • 19
  • 35
developer_hatch
  • 15,898
  • 3
  • 42
  • 75