Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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") logger.setLevel(logging.DEBUG)  # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG)  # create formatter formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")  # add formatter to ch ch.setFormatter(formatter)  # add ch to logger logger.addHandler(ch)  # "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.

like image 771
Hai Vu Avatar asked Jul 10 '10 17:07

Hai Vu


People also ask

What is logging getLogger (__ Name __)?

getLogger(name) is typically executed. The getLogger() function accepts a single argument - the logger's name. It returns a reference to a logger instance with the specified name if provided, or root if not. Multiple calls to getLogger() with the same name will return a reference to the same logger object.

Is Python logging built in?

Python has a built-in module logging which allows writing status messages to a file or any other output streams.


2 Answers

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") 
like image 89
Metalshark Avatar answered Sep 19 '22 09:09

Metalshark


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 
like image 40
Ben Avatar answered Sep 20 '22 09:09

Ben