Is there a way to make the Python logger output dates in ISO8601 format?
My logger is set up like this...
logging.basicConfig(
format="%(message)s - %(asctime)s)
From the Python docs (located here: https://docs.python.org/2/howto/logging.html) you can see the following:
The default format for date/time display (shown above) is ISO8601. If you need more control over the formatting of the date/time, provide a datefmt argument to basicConfig, as in this example:
The only problem is that the date output is not ISO8601 format. The date output by the above formatter is:
2018-06-15 11:07:41,454
This is not ISO8601 format as defined here: https://en.wikipedia.org/wiki/ISO_8601
What is the easiest way to get the date in the correct format? Can this be done out of the box or do I need to import a package to do it?
I've tried adding a date formatter e.g. datefmt="%Y-%m-%dT%H:%M:%S.%f %Z"
but some of the formatting characters were not recognised - namely %f
and %Z
gave a textual description of the timezone and not a numeric offset.
import logging logging. basicConfig( format='%(asctime)s %(levelname)s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S' ) logging.info('Just a random string...') # 2030-01-01 00:00:00 INFO Just a random string...
Python - Print Logs in a File. If you want to print python logs in a file rather than on the console then we can do so using the basicConfig() method by providing filename and filemode as parameter. The format of the message can be specified by using format parameter in basicConfig() method.
Logging is a Python module in the standard library that provides the facility to work with the framework for releasing log messages from the Python programs. Logging is used to tracking events that occur when the software runs. This module is widely used by the developers when they work to logging.
This works for me in most situations:
logging.basicConfig(
format="%(asctime)s %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S%z"
)
The output looks like:
2019-11-09T01:18:13-0800 Something logged here
A one-liner I've been using to include miliseconds:
logging.Formatter.formatTime = (lambda self, record, datefmt=None: datetime.datetime.fromtimestamp(record.created, datetime.timezone.utc).astimezone().isoformat(sep="T",timespec="milliseconds"))
The output looks like
2021-08-05T22:43:02.985614+00:00 Something logged 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