0

I'm trying to make a logger, which will create a new .log file every time the code is executed. The .log file should have the following format info_24/03/2017_13:00:00.log. I'm trying to achieve this with strftime however an error is raised when I try to run the code.

#!/usr/bin/python3
import logging
from time import strftime

def main():
    datestr = strftime('[%d/%m/%Y %T]')
    logfile = 'info_{}.log'.format(strftime('%d/%m/%Y_%T'))
    logformat = '%(asctime)s %(levelname)s %(message)s'

    logging.basicConfig(filename=logfile, filemode='w', level=logging.INFO, format=logformat, datefmt=datestr)

    print('Hello world!')
    logging.info('Program executed')

if __name__ == '__main__':
    main()

When I remove strftime from filename, program runs okay. Obviously though, it doesn't have the desired effect. Otherwise, here's the error.

Traceback (most recent call last):
  File "./log_example.py", line 16, in <module>
    main()
  File "./log_example.py", line 10, in main
    logging.basicConfig(filename=logfile, filemode='w', level=logging.INFO, format=logformat, datefmt=datestr)
  File "/usr/lib/python3.5/logging/__init__.py", line 1744, in basicConfig
    h = FileHandler(filename, mode)
  File "/usr/lib/python3.5/logging/__init__.py", line 1008, in __init__
    StreamHandler.__init__(self, self._open())
  File "/usr/lib/python3.5/logging/__init__.py", line 1037, in _open
    return open(self.baseFilename, self.mode, encoding=self.encoding)
FileNotFoundError: [Errno 2] No such file or directory: '/home/estilen/Dropbox/College/Year_3/CSA2/Python/Examples/Logging/info_24/03/2017_13:04:29.log'

I'm aware of rotating log files, but I wanted to get this to work anyway. How do I go about fixing the code to achieve my goal?

Luke
  • 744
  • 2
  • 7
  • 23

1 Answers1

2

You should modify this line:

logfile = 'info_{}.log'.format(strftime('%d/%m/%Y_%T'))

Try to replace it with other characters like strftime('%d_%m_%Y_%T').

Do not use / in a filename in Linux.

See more details from Is it possible to use “/” in a filename?

Community
  • 1
  • 1
McGrady
  • 10,869
  • 13
  • 47
  • 69
  • Thanks! Completely forgot the slash would make it think it's in a further directory. – Luke Mar 24 '17 at 13:17