Android Code Snippet Application Log File Function

Hello All

Have been using this for years, thought I might shared it.
It's a logger function, it's very handy when you have multiple app and your trying to see who doing what.

Hope someone might find it useful


Regards

John.

B4X:
Sub writelog(m As String)
   
   Dim s As OutputStream, b() As Byte  
   Dim TimeFormat, myTimeFormat As String
   
   Try
       ' // save existing time format
       TimeFormat = DateTime.TimeFormat
               
       myTimeFormat = "HH:mm:ss.SSS"
       ' // set date time format
       DateTime.TimeFormat = myTimeFormat
       ' // debugger logging
       Log(DateTime.Date(DateTime.Now) & " " & DateTime.time(DateTime.Now) & " - APP NAME - " & m)
       ' // create log data for file
       m = DateTime.Date(DateTime.Now) & " " & DateTime.time(DateTime.Now) & " - " & m & Chr(10) & Chr(13)
       ' // restore date time format
       DateTime.TimeFormat = TimeFormat
       
       b = m.GetBytes("UTF8")
       
       If File.ExternalWritable = False Then
           If File.Size(File.DirInternal, "app_name.log") >= 8388608 Then
               File.Delete(File.DirInternal, "app_name.log")
           End If
           s = File.OpenOutput(File.DirInternal, "app_name.log", True)
           
       Else
           If File.Size(File.DirDefaultExternal, "app_name.log") >= 8388608 Then
               File.Delete(File.DirDefaultExternal, "app_name.log")
           End If
           s = File.OpenOutput(File.DirDefaultExternal,"app_name.log", True)
       End If
       
       s.WriteBytes(b,0,b.Length -1)
       s.Flush
       s.close

       
   Catch
       'ToastMessageShow("writelog, error - " & LastException.Message,True)
       Log("writelog, error - " & LastException.Message)
       Log("writelog, m =  " & m)
   End Try
       
   
End Sub
 

AnandGupta

Expert
Licensed User
Longtime User
Hi John,

I use similar one in my windows application for logging, but instead of deleting the log file if more than maximum defined size, I reduce it to minimum defined size, keeping the last log entries. Can you enhance the b4a code similarly, if possible ?

Also for linefeed we use Chr(13) & Chr(10), i.e. reverse.

Regards,

Anand
 

Jmu5667

Well-Known Member
Licensed User
Longtime User
Hi Anand

You could rename the existing log file to my_app_prevxxmb.log instead of deleting it.. You should be able to modify it yourself, I just posted it as is

Regards

John
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…