0

I have a program which is set to run for a long period of time and I keep a log file to keep track of the events. However, the size of the log file is getting bigger as time goes by.

I would like to keep a log file everyday instead of just one log file for everything.

This is my current code:

logging.basicConfig(filename='myfile.log',level=logging.INFO)

I want to set a date for the log file such that, it will become myfile_DDMMYYYY.log and creates another log file everyday with the different date.

Any idea if it is possible to be done ?

decemberrobot
  • 451
  • 2
  • 9
  • 20
  • you can concatenate filename with `str(datetime.date.today())` and use `time.sleep` to write the log every other day. – umutto Mar 10 '17 at 03:32
  • Does this answer your question? [Want datetime in logfile name](https://stackoverflow.com/questions/9135936/want-datetime-in-logfile-name) – Josh Correia Jul 14 '20 at 17:19

2 Answers2

0
>>> import datetime
>>> now = datetime.datetime.now()
>>> filename = now.strftime('myfile_%d%m%Y.log')
>>> filename
'myfile_09032017.log'

the easiest way to get a new log every day would be to simply exit after 24 hours, and have Upstart or inittab restart it for you with respawn.

jcomeau_ictx
  • 37,688
  • 6
  • 92
  • 107
0

I typically do something like this:

logger = logging.getLogger('abcd')
logger.setLevel( logging.INFO )
fH     = logging.FileHandler(os.path.join(
            'folderName', 
            dt.now().strftime('%Y-%m-%d--%H-%M-%S')+'_value.log'))
ssm
  • 5,277
  • 1
  • 24
  • 42