When I create my logfile, I want the name to contain the datetime.
In Python you can get the current datetime as:
>>> from datetime import datetime >>> datetime.now() datetime.datetime(2012, 2, 3, 21, 35, 9, 559000) The str version is
>>> str(datetime.now()) '2012-02-03 21:35:22.247000' Not a very nice str to append to the logfile name! I would like my logfile to be something like:
mylogfile_21_35_03_02_2012.log Is there something Python can do to make this easy? I am creating the log file as:
fh = logging.FileHandler("mylogfile" + datetimecomp + ".log")
I'd use YYYY-MM-DD HHmmss for filenames, unless there is a particular need for timezones or a possible need to parse them into ISO dates; in those cases an ISO date would probably be preferrable.
now() function Return the current local date and time, which is defined under datetime module.
You need datetime.strftime(), this allows you to format the timestamp using all of the directives of C's strftime(). In your specific case:
>>> datetime.now().strftime('mylogfile_%H_%M_%d_%m_%Y.log') 'mylogfile_08_48_04_02_2012.log'
You could also use a TimedRotatingFileHandler that will handle the date and the rollover every day (or whenever you want) for you.
from logging.handlers import TimedRotatingFileHandler fh = TimedRotatingFileHandler('mylogfile', when='midnight') By default the format will be depending on the rollover interval:
The system will save old log files by appending extensions to the filename. The extensions are date-and-time based, using the strftime format
%Y-%m-%d_%H-%M-%Sor a leading portion thereof, depending on the rollover interval.
But you can modify that as showed here, by doing something like:
from logging.handlers import TimedRotatingFileHandler fh = TimedRotatingFileHandler('mylogfile', when='midnight') fh.suffix = '%Y_%m_%d.log'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With