An Easier Way to Name Log Files with the Current Date and Time
Windows NT's Date and Time commands let you automatically name log files.
August 26, 2003
Reader to Reader: "Automatically Name Log Files with the Current Date and Time" (February 2002, http://www.winnetmag.com, InstantDoc ID 23468) uses the Ntdate command, which is in Jeffery Harris's ANITX Toolset, to automatically name log files. However, Windows NT's Date and Time commands are more than adequate for this task.
I wrote the batch file that Listing 1 shows to create date- and time-specific logs. This batch file, which requires NT 4.0 or later with command-line extensions, sets several variables, including date (yyyymmdd), time of day (hhmmss), and timestamp (yyyymm-ddhhmmss-nn, where nn is hundredths of seconds). To timestamp records, you can run the code that Listing 2 shows to create a daily log file (yyyymmdd.log) and stamp each record with the time of day to 1-second accuracy (hhmmss). If you need multiple log files for the same day, you can replace the first three lines with
call GetTimeStamp mydateecho %timestamp% log file %mydate%.log created. > %mydate%.log
to create a log file (yyyymmdd-hhmmss-nn.log) with date and timestamps to within 1/100 second.
To work on NT 4.0, GetTimeStamp.bat needs to trick the Time command into returning through the command
time ~datetime.txt
Then, the batch file parses the first line of the output file. (The first For/f command could instead use Date/T, but the second can't use Time/T because Time/T displays time in a 12-hour clock format.)
Windows 2000 offers a more elegant solution. GetTimeStamp.bat can dispense with writing and reading ~datetime.txt and simply use the %time% and %date% environment variables. The For/f commands become
for /f "tokens=1-4 delims=/ " %%i in ("%date%")for /f "tokens=1-4 delims=.: " %%i in ("%time%")
—Richard Gutter
[email protected]
About the Author
You May Also Like