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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With