how can I create a file that takes the name date-time.log

0
import datetime
fecha = str(datetime.datetime.now())+str('test.log')
print (fecha)--> 2018-10-30 09:18:29.606405test.log

Why does the python console execute me and take out the name I want and when executing it in the code, no?

the line on which I use the date is this

handler = logging.handlers.TimedRotatingFileHandler(filename = fecha, 
when='m', interval=1, backupCount=5)

Instead of interpreting the valos of the variable the file calls it date Could someone give me a solution or a clue?

    
asked by antoniop 30.10.2018 в 14:02
source

1 answer

1

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.

    
answered by 30.10.2018 / 15:44
source