0

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?

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer. Tested to work successfully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.