user9347473
user9347473

Reputation:

Add the time in a log name using logger

I am trying to add in multiple log files into a Logs folder, but instead of having to change the code each time you start the program, i want to make the log file's name "Log(the time).log". I'm using logger at the moment, but i can switch. I've also imported time.

Edit: Here is some of the code i am using:

import logging
logger = logging.getLogger('k')
hdlr = logging.FileHandler('Path to the log file/log.log')
formatter = logging.Formatter('At %(asctime)s, KPY returned %(message)s at level %(levelname)s
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
logger.info('hello')

Upvotes: 2

Views: 744

Answers (3)

user9347473
user9347473

Reputation:

I got help from another website.

You have to change the hdlr to:

({FOLDER LOCATION}/Logs/log{}.log'.format(datetime.datetime.strftime(datetime.datetime.now(), '%Y%m%d%H%M%S_%f')))

Upvotes: 0

wim
wim

Reputation: 363213

import logging
import time

fname = "Log({the_time}).log".format(the_time=time.time())
logging.basicConfig(level=logging.DEBUG, filename=fname)

logging.info('hello')

Upvotes: 1

Ryan Schaefer
Ryan Schaefer

Reputation: 3120

You should do it when you set the FileHandler for the logging object. Use datetime instead of time so that you can include the date for each instance of the log in order to differentiate logs on different days at the same time.

fh = logging.FileHandler("Log"+str(datetime.datetime.now())+'.log')
fh.setLevel(logging.DEBUG)

Upvotes: 0

Related Questions