user3848207
user3848207

Reputation: 4917

Make timestamp appear in log file automatically

I am using python 3.7 logging module. This is how it is configured.

import logging
import os

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s-%(levelname)s-%(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
fh = logging.FileHandler(os.getcwd() + "/log/" + os.path.basename(__file__) + ".log")
logger.addHandler(fh)

The code works fine. However, I want timestamps to be added to each row of entry in the log file.

Currently, if I run logger.info("new log entry"), the log file will have a new line added that looks like this;

new log entry

What I want is to have timestamp prepended on each new line added to the log file to look something like this;

2020-04-22 11:11:16 new log entry

How do I configure the logger to do this?

Upvotes: 0

Views: 191

Answers (1)

chron0x
chron0x

Reputation: 995

You have to configure the FileHandler logger in the same way you configured the StreamHandler:

fh = logging.FileHandler(os.getcwd() + "/log/" + os.path.basename(__file__) + ".log")
fh.setLevel(level=logging.DEBUG)
fh_formatter = logging.Formatter('%(asctime)s-%(levelname)s-%(message)s')
fh.setFormatter(fh_formatter)
logger.addHandler(fh)

Upvotes: 2

Related Questions