B4J Code Snippet Log Stack Trace

SubName: LogStackTrace

Description:
Display the log trace from any point in your app. Useful for tracking where a sub is being called from without forcing the app to crash.

B4X:
'Log the current stacktrace
'FromSubName will limit the log to items created before the named sub was called
'Limit will only display that number of items
Public Sub LogStackTrace(FromSubName As String,Limit As Int)
    Dim StackTrace() As Object
    Dim Throwable As JavaObject
    Dim i As Int = 0
    Dim Found As Boolean = False
    Dim JO As JavaObject
  
    'Initialize a new throwable from which to get the stacktrace
    Throwable.InitializeNewInstance("java.lang.Throwable",Null)
  
    'Get the stacktrace into an Object Array
    StackTrace = Throwable.RunMethod("getStackTrace",Null)
  
    'Check if list all is requested
    If Limit = -1 Then Limit = StackTrace.Length - 1
  
    Log("Log Stack Trace ###############################")
    If FromSubName <> "" Then Log("From Sub " & FromSubName)
    Log(" ")
  
    'Check if we only want to Log items before the named sub
    If FromSubName <> "" Then
        For i = 0 To StackTrace.Length - 1
            JO = StackTrace(i)
            Dim S As String = JO.RunMethod("toString",Null)
            If S.Contains("._" & FromSubName.ToLowerCase) Then
                Found = True
                i = i + 1
                Exit
            End If
        Next
        If Not(Found) Then
            Log("Sub " & FromSubName & " Not found in stacktrace")
            Return
        End If
    End If
  
    'Make sure there are enough items in the stacktrace so that the requested Limit will not cause an Out of bounds error otherwise just show all items.
    If i + Limit >= StackTrace.Length Then Limit = StackTrace.Length - i
  
    'Log the required stacktrace items
    For j = i To i + Limit - 1
        JO = StackTrace(j)
        Log(JO.RunMethod("toString",Null))
    Next
    Log(" ")
    Log((j - i) & " items Listed #######################")
End Sub

If you Pass a subname, it will limit the output to items generated before the sub was run.

If you pass a Limit. only that number of items will be displayed (assuming there are that many in the log)

It should work on B4a too, not too sure about total compatibility with Rapid debuging. but should be OK with Legacy debugging and Release mode (if you connect via USB)



Depends on: JavaObject

Tags: B4j B4a Log Stack Trace
 
Last edited:

stevel05

Expert
Licensed User
Longtime User
I was using it a lot yesterday with B4j and it seemed to work just fine. So hopefully no issues.
 
Top