I have not been able to reproduce what you mention, but definitely the name you use, as you have already been told, is not a valid name for many operating systems. In Linux it is true, it should work, in Windows definitely not, you should get an exception of type OSError
.
I recommend that you give to date a format compatible with all operating systems, preferably removing problematic characters such as :
scripts and spaces. You can use strftime()
in the following way:
LOG_FILENAME = datetime.datetime.now().strftime("%Y%m%d_%H%M%Stest.log")
print(LOG_FILENAME)
20181030_143434test.log
On the other hand, using a date as a file name in a TimedRotatingFileHandler
is unusual, in these cases it is more common to give a generic name to the log (without date), and the handler will be responsible for renewing the files to as time passes and renaming the files with the date of rotation.
A functional example could be:
import glob
import logging
import logging.handlers
import datetime
import time
LOG_FILENAME = datetime.datetime.now().strftime("%Y%m%d_%H%M%Stest.log")
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
# Definimos el handler a efectos de prueba, el intervalo lo dejamos en 1 seg
handler = logging.handlers.TimedRotatingFileHandler(filename = LOG_FILENAME,
when='s', interval=1, backupCount=5)
my_logger.addHandler(handler)
# Logeamos unos cuantos mensajes de prueba
for i in range(10):
time.sleep(1)
my_logger.debug('i = %d' % i)
# Vemos que archivos creo el loop anterior
logfiles = glob.glob('%s*' % LOG_FILENAME)
for filename in logfiles:
print(filename)
20181030_113112test.log
20181030_113112test.log.2018-10-30_11-31-17
20181030_113112test.log.2018-10-30_11-31-18
20181030_113112test.log.2018-10-30_11-31-19
20181030_113112test.log.2018-10-30_11-31-20
20181030_113112test.log.2018-10-30_11-31-21
The last cycle will list the names of the generated log files, the rotation is defined in 1 second to notice exactly this behavior. You can see that the base name of the file is maintained and every second approximately a rotation of the log would be generated. The original name 20181030_113112test.log
always represents the current log.