After implementing some logging in my system, I got tired of digging through very long files trying to determine where specific runs started/stopped to look for differences, so I began adding a date/time stamp to the file name so I'd get a new log file each time the processing kicked off. This was wonderful, but solving one problem created a new one - now I have a proliferation of log files and I have to keep the collection of files under control.
I've written the following procedure to do the pruning and it works quite well. I'm wondering if there are any gotcha's I may have missed in my extensive (2 hours of) testing, or if there are any more efficient ways of doing this.
I believe the implementation is fairly efficient. There's no need to keep a list of the
naxLogsToKeep newest (or oldest) files in memory, only the one I'm looking at now and the one known to be the oldest I've looked at so far. By not having an array, collection, dictionary or other structure of all the files, there's no need to sort anything, so this should be fairly efficient. But, I don't know it all, so I'm open to suggestions.
There are some situations that I'm aware of:
- What happens if
filePathdoesn't have a trailing slash? It's already been checked in the calling procedure. I suppose it should be checked here again, just in case I ever reuse this code.
- The error handling is... weak. Yup. I threw something in there just for giggles and grins, but will probably remove it and let it bubble up to be dealt with at a higher level.
- It doesn't work well if there are more than
Dir()gives you no indication whatsoever of what order you'll get files, if there are extra files than this will delete the oldest one(s) it's come across when it hits
maxLogsToKeep. I'm pretty sure, in my limited testing, that it will work just fine, once there are only
maxLogsToKeeplog files in the given directory.
With that, the code:
Private Sub DeleteExtraLogFiles(ByVal filePath As String, ByVal fileNamePattern As String, ByVal maxLogsToKeep As Long) On Error GoTo ErrorHandler Dim fileCount As Long Dim oldestFileDate As Date oldestFileDate = #12/31/3999# Dim currentFile As String currentFile = Dir(filePath & fileNamePattern) Do While Len(currentFile) > 0 fileCount = fileCount + 1 Dim currentFileDate As Date currentFileDate = FileDateTime(filePath & currentFile) If fileCount < maxLogsToKeep Then If currentFileDate < oldestFileDate Then Dim oldestFile As String oldestFile = currentFile oldestFileDate = currentFileDate End If Else If currentFileDate < oldestFileDate Then Kill filePath & currentFile Else Kill filePath & oldestFile oldestFile = currentFile oldestFileDate = currentFileDate End If End If currentFile = Dir Loop CleanExit: Exit Sub ErrorHandler: With Err MsgBox "Error: " & .Number & vbCrLf & .Description End With Resume CleanExit End Sub