Find and Fix Bugs with Apex Replay Debugger

Set breakpoints and checkpoints to step through code and inspect variable values at specific line numbers in a debug session. Invoke Apex tests and download debug logs using Visual Studio Code. Find and fix a bug using Apex Replay Debugger for Visual Studio Code.

Launch Your Trailhead Playground

  • Introduction
    • “Any bug not detected in the design phase will cost ten times more time to detect at the coding phase and an additional ten times more at the debugging phase.” — Dr. Nikolai Bezroukov, The Art of Debugging
      • IE, catching bugs sooner in the process is better
    • Debugging is distinct from Testing in software development
      • Testing: attempts to find and report errors
      • Debugging: attempts to identify the cause of those errors and fix them
    • Apex provides testing support with a framework for isolated execution of Apex tests:
      • Includes nonproduction orgs such as sandboxes/scratch orgs:
      • Debugging support through System.debug statement, debug logs, and debuggers
    • When trace flags are enabled, Apex code generates debug logs, which are recordings of all interactions in a transaction
      • Apex Replay Debugger simulates a live debugging session using a debug log
      • Presents the logged information, including variable values, call stack, and breakpoints, similar to an interactive debugger
  • What is Apex Replay Debugger?
    • Free tool that allows you to debug your Apex code by inspecting debug logs using VS Code as the client
      • Gives you the same features you expect from other debuggers:
        • View variables, set breakpoints, hover over variables to see their current value
        • Idea is that you no longer need to parse through long log files manually or use System.debug statements to see variable values/track execution path
    • Makes it easy to work asynchronously and collaboratively solve problems
      • Launch a replay debugger session from any replay-enabled debug log, so clients and coworkers can share debug logs to help each other solve problems
      • Start a debugging session by opening a debug log in VS Code and right-clicking any line in the file to launch debugger

  • What is Apex Interactive Debugger?
    • Apex Interactive Debugger allows customers to debug their Apex code on sandboxes and scratch orgs in real time using VS Code
    • Comes with features for independent software vendor partners (ISVs) working with subscribers who install a managed package
    • Apex Interactive Debugger and ISV Customer Debugger are paid products
    • Rest of this page focuses on setting up and using the free Apex Replay Debugger

Set Up Visual Studio Code

  • Set Up Visual Studio Code
    • Apex Replay Debugger is part of the Salesforce Extension Pack for VS Code
      • Extensions require VS Code, Salesforce CLI, and Java 11 or 8
  • Install and Update Salesforce CLI
  • Install and Update Visual Studio Code
  • Install and Update Salesforce Extensions for Visual Studio Code
    1. In VS Code, click the View menu and then choose Extensions
    2. Then enter salesforce extension pack in search box
    3. Then click Install or Update from the Salesforce Extension Pack result
    4. Once installed, relaunch Visual Studio Code to ensure the changes take effect
  • Install Java Platform Standard Edition Development Kit
    • Apex support in Salesforce Extensions for Visual Studio Code depend on the Java Platform, Standard Edition Development Kit (JDK)
    • Requires an installation of either JDK version 17 (recommended), JDK version 11, or JDK version 8
    1. Install Java according to recommendations in Salesforce Extensions documentation
    2. Confirm Java is installed by finding its installation directory.
      • Ex, for JDK8 update 201:
        • Windows: C:\Program Files\Java\jdk1.8.0_201
        • MacOS: /Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home
      • To determine this location from the command line, on Mac, run:
        • /usr/libexec/java_home to get the default JDK location
        • /usr/libexec/java_home -V to find all installed JDKs
  • Configure Java Home Setting for Apex Support
    • In VS Code, go to Code > Preferences > Settings on macOS, File > Preferences > Settings on Windows, enter apex java in the search, then in the salesforcedx-vscode-apex.java.home enter the Java installation directory you want to use, relaunch VS Code, open a terrminal window, and run java -version to ensure the setting worked

Set Up Apex Replay Debugger

  • Create a Salesforce DX Project
    • Use Cmd+Ship+P in VS Code, then the sfdx create project command
    • See Trailhead for more details
  • Create an Apex Class
    • In VS Code, right-click classes, then choose SFDX: Create Apex Class, create the class below
    • See Trailhead for more details
public with sharing class AccountService {
  public Account createAccount( String accountName, String accountNumber, String tickerSymbol ) {
    Account newAcct = new Account(
      Name = accountName,
      AccountNumber = accountNumber,
      TickerSymbol = accountNumber
    );
    return newAcct;
  }
}
  • Create an Apex Test
    • In VS Code, right-click classes, then choose SFDX: Create Apex Class, create the class below
    • See Trailhead for more details
@IsTest
private class AccountServiceTest {
  @IsTest
  static void should_create_account() {
    String acctName = 'Salesforce';
    String acctNumber = 'SFDC';
    String tickerSymbol = 'CRM';
    Test.startTest();
      AccountService service = new AccountService();
      Account newAcct = service.createAccount( acctName, acctNumber, tickerSymbol );
      insert newAcct;
    Test.stopTest();
    List<Account> accts = [ SELECT Id, Name, AccountNumber, TickerSymbol FROM Account WHERE Id = :newAcct.Id ];
    System.assertEquals( 1, accts.size(), 'should have found new account' );
    System.assertEquals( acctName, accts[0].Name, 'incorrect name' );
    System.assertEquals( acctNumber, accts[0].AccountNumber, 'incorrect account number' );
    System.assertEquals( tickerSymbol, accts[0].TickerSymbol, 'incorrect ticker symbol' );
  }
}
  • Authorize an Org
    • Use Cmd-Shift-P then sfdx authorize org, selecting the default org option for Trailhead orgs
    • See Trailhead for more details

Debug Your Code

  • Deploy Metadata to Org
    • In VS Code, right-click the folder classes then choose SFDX: Deploy Source to Org
    • If the command fails, try restarting VS Code
  • Run Apex Tests
    • Cmd+Shift+P, then enter apex test in the search box, then choose SFDX: Run Apex Tests, then select the test you want to run
    • Note that running AccountServiceTest with the code from above will result in a failure:
      • Error message indicates the wrong value was assigned to the account’s ticker symbol field
      • Next steps, below, involve setting a checkpoint in the code, rerunning the test to collect a log, and replaying the debug log to find our code bug

  • Set Breakpoints and Checkpoints
    • When debugging, Breakpoints instruct the running program to pause at a specific line number so the developer can inspect variable values at that point in time
      • Set as many breakpoints as you want
      • Display as a solid red dot
    • Checkpoints are a type of Breakpoint that provides more information by capturing heap dumps
      • Can set up to 5 checkpoints at a time
      • Display as a red circle with a line through the center
    • Use Debug: Toggle Breakpoint and SFDX: Toggle Checkpoint commands to toggle on and off breakpoints and checkpoints
    1. Place your cursor on the line where you want to add a checkpoint
    2. Cmd+Shift+P, search for sfdx checkpoint, then select SFDX: Toggle Checkpoint. A checkpoint will show up on that line of code.
    3. Cmd+Shift+P, search for sfdx checkpoint, then select SFDX: Update Checkpoints in Org. This step tells Salesforce about the checkpoints so that heap dumps are collected as Apex code executes.
      • Note that checkpoints expire after 30 minutes and heap dumps expire after a day

  • Run Apex Test and Get Debug Logs
    1. Cmd+Shift+P, then search for sfdx replay, then select SFDX: Turn On Apex Debug Log for Replay Debugger
    2. Cmd+Shift+P, then search for apex text, then choose SFDX: Run Apex Tests, then choose the tests you want
    3. Now, running the test will generate a replay-enabled debug log and checkpoints to help find the bug
    4. Cmd+Shift+P, then search for sfdx get, then choose SFDX: Get Apex Debug Logs

  • Replay an Apex Debug Log
    1. Open the debug log
    2. Right-click any line in the debug log then choose SFDX: Launch Apex Replay Debugger with Current File
    3. Select the “Play Icon” in the Debug Toolbar to continue to the first breakpoint
    4. At that point, the Apex Replay Debugger pauses on the line. The Debug sidebar displays the current variable values in scope. Use this information to debug the class.

  • Deploy Fixed Metadata to Org
    • The line that needs to be fixed in AccountService.cls, above, is the following.
    • Update it, then right-click and choose SFDX: Deploy This Source to Org
TickerSymbol = tickerSymbol
  • Run Apex Tests to Verify Fix
    • To re-run tests, Cmd+Shift+P, then search for apex test, then choose SFDX: Run Apex Tests
    • Following the fix above, the Apex tests pass