Search code examples
vb6

VB6 - How to create another log file if reach atleast 5mb


The application is hanging up when it the log file reached 5mb. I just want to create another log file or incremental log file when reached certain size and write into this file. Could you provide some sample or functions that I can use. Below is my current function and planning to use FileLen to check file size.

TIA.

Public Sub LogTraces(ByVal folderName As String, ByVal sLocation As String, _
                     ByVal message As String)
                               
    Dim intN As Integer
    
    intN = FreeFile(1)

    Open sLocation & "\" & UCase(folderName) & "\" & UCase(folderName) & "_LOG_" & Format(Now, "MMDDYYYY") & ".log" For Append Shared As #intN
    'Open sLocation & "\LOGS\" & ConnectionID & "-" & Format(Date, "yyyymmdd") & ".log" For Append Shared As #intN

    Print #intN, Format(Now, "[mmddyyyy HH:mm:ss]") & ": " & message
        
    Close #intN
   
End Sub

Solution

  • I tweaked your code by using a function to calculate the file name.

    Option Explicit
    
    Public Sub LogTraces(ByVal folderName As String, ByVal sLocation As String, ByVal message As String)
       Dim fn As Integer: fn = FreeFile(1)
       Open GetFileName(folderName, sLocation) For Append Shared As #fn
       Print #fn, Format(Now, "[mmddyyyy HH:mm:ss]") & ": " & message
       Close #fn
    End Sub
    
    Public Function GetFileName(ByVal folderName As String, ByVal sLocation As String) As String
       Dim i As Integer
       
       'get 'base' file name and make sure it exists
       GetFileName = sLocation & "\" & UCase(folderName) & "\" & UCase(folderName) & "_LOG_" & Format(Now, "MMDDYYYY") & ".log"
       If Dir(GetFileName) = "" Then CreateFile GetFileName
       
       'if the file is too big (pick some file size in bytes)
       Do While FileLen(GetFileName) > 5242880
          'get new file name by appending a number and make sure it exists
          i = i + 1
          GetFileName = sLocation & "\" & UCase(folderName) & "\" & UCase(folderName) & "_LOG_" & Format(Now, "MMDDYYYY") & "_" & i & ".log"
          If Dir(GetFileName) = "" Then CreateFile GetFileName
       Loop
    End Function
    
    Public Sub CreateFile(ByVal FileName As String)
       Dim fn As Integer: fn = FreeFile(1)
       Open FileName For Output As #fn
       Close #fn
    End Sub