Reputation: 1781
I get log messages with the same date when I print them to the console (or logfile). But the time-out between messages is two seconds. Here is my code
folder = "logs"
log_name = {}.log
file_name = os.path.join(folder, log_name)
date_format = "%Y-%m-%d_%H:%M:%S"
name_format = "[%(asctime)s] [%(levelname)s] [%(filename)s:%(lineno)s] - %(message)s"
log = logging.getLogger('')
log.setLevel(logging.DEBUG)
format = logging.Formatter(name_format, datetime.now().strftime(date_format))
console_handler = logging.StreamHandler(sys.stderr)
file_handler = handlers.RotatingFileHandler(filename=datetime.now().strftime(file_name.format(date_format)),
maxBytes=(1048576*5),
backupCount=7)
console_handler.setFormatter(format)
file_handler.setFormatter(format)
log.addHandler(console_handler)
log.addHandler(file_handler)
from time import sleep
log.info("1")
sleep(2)
log.info("2")
sleep(2)
log.info("3")
Here is output:
[2017-07-08_17:20:51] [INFO] [logs.py:112] - 1
[2017-07-08_17:20:51] [INFO] [logs.py:114] - 2
[2017-07-08_17:20:51] [INFO] [logs.py:116] - 3
Upvotes: 2
Views: 243
Reputation: 46869
have a look at the documentation of logging.Formatter(fmt=None, datefmt=None, style='%')
. the second argument you need to pass is a datefmt
("%Y-%m-%d_%H:%M:%S"
in your case). the logger will do the fmt.strftime(...)
for you.
you are passing a string that represents datetime.now()
in this format. as this is a str
(e.g. '2017-07-08_17:20:51'
) the formatter does not complain but always prints this exact date: '2017-07-08_17:20:51'.strftime(...)
will result in '2017-07-08_17:20:51'
- there are no format specifiers to fill in.
what you should do is this:
fmt = logging.Formatter(name_format, date_format)
# instead of
# format = logging.Formatter(name_format, datetime.now().strftime(date_format))
(btw: format
is a built-in; renamed your formatter to fmt
such that the built-in is not overwritten).
Upvotes: 6