Hai Vu Hai Vu - 1 year ago 73
Python Question

How to Customize the time format for Python logging?

I am new to Python's logging package and plan to use it for my project. I would like to customize the time format to my taste. Here is a short code I copied from a tutorial:

import logging

# create logger
logger = logging.getLogger("logging_tryout2")

# create console handler and set level to debug
ch = logging.StreamHandler()

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

# add formatter to ch

# add ch to logger

# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

And here is the output:

2010-07-10 10:46:28,811;DEBUG;debug message
2010-07-10 10:46:28,812;INFO;info message
2010-07-10 10:46:28,812;WARNING;warn message
2010-07-10 10:46:28,812;ERROR;error message
2010-07-10 10:46:28,813;CRITICAL;critical message

I would like to shorten the time format to just: '
2010-07-10 10:46:28
', dropping the mili-second suffix. I looked at the Formatter.formatTime, but confused. I appreciate your help to achieve my goal. Thank you.

Answer Source

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")


# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
                              "%Y-%m-%d %H:%M:%S")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download