How to Customize the time format for Python logging?
From the official documentation regarding the Formatter class:
The constructor takes two optional arguments: a message format string and a date format string.
So change
# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")
to
# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
"%Y-%m-%d %H:%M:%S")
Using logging.basicConfig
, the following example works for me:
logging.basicConfig(
filename='HISTORYlistener.log',
level=logging.DEBUG,
format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
)
This allows you to format & config all in one line. A resulting log record looks as follows:
2014-05-26 12:22:52.376 CRITICAL historylistener - main: History log failed to start