Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Logging Module logging timestamp to include microsecond

Tags:

I am using python's logging module for logs, but needed the timestamp to include microsecond. It seems the timestamp can only get as precise as millisecond. Here's my test code

import logging

logging.basicConfig(format='%(asctime)s %(levelname)s {%(module)s} [%(funcName)s] %(message)s',

    datefmt='%Y-%m-%d,%H:%M:%S:%f', level=logging.INFO)

class log2_test():

    def test_class(self):

        logging.warning("Warning2 inside the class")

def get_started2():

    logging.info("Logged2 Here")

if __name__ == '__main__':
    get_started2()

Here's the output I get --

2015-07-09,16:36:37:f INFO {logger} [get_started2] Logged2 Here

Somehow, %f is not recognized. Python version is 2.7.6.

How do I get the timestamp to include microseconds? Thanks in advance.

like image 980
Han Gu Avatar asked Jul 09 '15 21:07

Han Gu


People also ask

How do I log a timestamp in Python?

We can log the timestamp to the console with the logging module easily by adjusting the basic configuration. import logging logging. basicConfig( format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S') logging.info('Message for the user.

How do I change the timezone in Python logging?

Formatter): converter = lambda *args: datetime. now(tz). timetuple() LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'Tokyo': { '()': TokyoFormatter, 'format': '%(asctime)s %(levelname)s: %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, }, 'handlers': { 'console': { 'class': 'logging.

Is logging a module in Python?

Python comes with a logging module in the standard library that provides a flexible framework for emitting log messages from Python programs. This module is widely used by libraries and is the first go-to point for most developers when it comes to logging.


1 Answers

According to the documentation, strftime() does not support %f. The logger provides milliseconds as a separate msecs attribute, so you could just add it yourself after the existing timestamp as follows:

logging.basicConfig(format='%(asctime)s.%(msecs)03d %(levelname)s {%(module)s} [%(funcName)s] %(message)s', datefmt='%Y-%m-%d,%H:%M:%S', level=logging.INFO)

This gave me the following output using your script:

2015-07-10,09:21:16.841 INFO {test script} [get_started2] Logged2 Here
like image 56
Martin Evans Avatar answered Sep 19 '22 04:09

Martin Evans