Capturing state
In order to capture the state of our class at a point in time, we will need to take the specific instance of the class and find a way of representing it that is both human-readable and simple to obtain. The prime way of doing this in Apex is with JSON, by serializing the class instance. We can then store this JSON as a file attached to the Log__c
record to allow us to view it later.
In order to ensure we comply with the Heap Size governor limit, we should make this method single-use only and persist any other logs separately. Our method to do this would look as follows:
public static void logWithState(String stackTrace, String logMessage, String logType, Object instance) { Log__c log = new Log__c(); log.Stack_Trace__c = stackTrace; log.Log_Message__c = logMessage; log.Type__c = logType; insert log; ...