Debugging is an important part in any programming development. In Apex, we have certain tools that can be used for debugging. One of them is the system.debug() method which prints the value and output of variable in the debug logs.
We can use the following two tools for debugging −
- Developer Console
- Debug Logs
Debugging via Developer Console
You can use the Developer console and execute anonymous functionality for debugging the Apex as below −
Example
Consider our existing example of fetching the customer records which have been created today. We just want to know if the query is returning the results or not and if yes, then we will check the value of List.
Paste the code given below in execute anonymous window and follow the steps which we have done for opening execute anonymous window.
Step 1 − Open the Developer console
Step 2 − Open the Execute anonymous from 'Debug' as shown below.
Step 3 − Open the Execute Anonymous window and paste the following code and click on execute.
// Debugging The Apex List<apex_customer__c> customerList = new List<apex_customer__c>(); customerList = [SELECT Id, Name FROM APEX_Customer__c WHERE CreatedDate = today]; // Our Query System.debug('Records on List are '+customerList+' And Records are '+customerList); // Debug statement to check the value of List and Size
Step 4 − Open the Logs as shown below.
Step 5 − Enter 'USER' in filter condition as shown below.
Step 6 − Open the USER DEBUG Statement as shown below.
Debugging via Debug Logs
You can debug the same class via debug logs as well. Suppose, you have a trigger in Customer object and it needs to be debugged for some variable values, then you can do this via the debug logs as shown below −
This is the Trigger Code which updates the Description field if the modified customer is active and you want to check the values of variables and records currently in scope −
trigger CustomerTrigger on APEX_Customer__c (before update) { List<apex_customer__c> customerList = new List<apex_customer__c>(); for (APEX_Customer__c objCust: Trigger.new) { System.debug('objCust current value is'+objCust); if (objCust.APEX_Active__c == true) { objCust.APEX_Customer_Description__c = 'updated'; System.debug('The record which has satisfied the condition '+objCust); } } }
Follow the steps given below to generate the Debug logs.
Step 1 − Set the Debug logs for your user. Go to Setup and type 'Debug Log' in search setup window and then click on Link.
Step 2 − Set the debug logs as following.
Step 3 − Enter the name of User which requires setup. Enter your name here.
Step 4 − Modify the customer records as event should occur to generate the debug log.
Step 5 − Now go to the debug logs section again. Open the debug logs and click on Reset.
Step 6 − Click on the view link of the first debug log.
Step 7 − Search for the string 'USER' by using the browser search as shown below.
The debug statement will show the value of the field at which we have set the point.