Sub topic 11
Running anonymous Apex and collecting debug logs
This chapter assumes you have a working Salesforce DX project in VS Code, an authorized default org, and the GreetingService class deployed to that org. If any of those are missing, finish the earlier chapters on project creation, org authorization, and deploying source first.
By the end you will be able to run a snippet of Apex without creating a class, read the debug log it produces, and control how much detail the log records. The next chapter uses these logs with the Apex Replay Debugger.
What anonymous Apex is
Anonymous Apex is Apex code that you compile and run on the server in one step, without saving it as a class or trigger in the org. The code runs in the context of the user you authorized. It is useful for:
- Trying a method quickly, without writing a test.
- Inspecting data or calling a service while you develop.
- Producing a debug log on demand, so you have something to inspect.
Anonymous Apex is not stored. Nothing you run this way appears in your org's code, and it does not count as deployed source. It does use the same governor limits as other Apex, and it can change data. A delete or update in an anonymous block is as real as one in a class.
The pieces involved
Running anonymous Apex touches three parts of the tooling. The editor sends your code to the org through the Salesforce CLI. The org compiles and runs it, and writes a debug log if logging is turned on for the running user. VS Code then shows the output.
Because the CLI does the work, the command uses whichever org is currently the default for the project. Check the org name in the status bar at the bottom of VS Code before you run anything that changes data.
Running your first snippet
The tutorial's anonymous snippet calls the GreetingService class:
System.debug(GreetingService.greet('Ada'));This works only if GreetingService exists in the org. If you have not deployed it, the compile step fails with a message such as Variable does not exist: GreetingService or Invalid type. Deploy force-app first.
There are two ways to run the snippet from the editor.
Run a whole file
- Create a folder named
scripts/apexin the project root. The Salesforce DX project template already includes it in many versions. Create it if it is missing. - Add a file named
hello.apexand paste the snippet into it. - Open the Command Palette (
Ctrl+Shift+Pon Windows and Linux,Cmd+Shift+Pon macOS). - Run SFDX: Execute Anonymous Apex with Currently Selected Text if you have selected code, or SFDX: Execute Anonymous Apex with Editor Contents to run the entire file.
Run a selection
Select one or more lines in any Apex file or scratch file. Run SFDX: Execute Anonymous Apex with Currently Selected Text. This is handy for testing one statement from a larger file.
Run it from the terminal instead
The CLI has an equivalent command that takes a file:
sf apex run --file scripts/apex/hello.apexIf you omit --file, the CLI prompts you to type or paste code and finish with Ctrl+D. The file form is easier to repeat and to put in version control.
Reading the output
A successful run prints a short status followed by the debug log. A log from the snippet above looks roughly like this:
Compiled successfully.
Executed successfully.
64.0 APEX_CODE,DEBUG;...
Execute Anonymous: System.debug(GreetingService.greet('Ada'));
11:42:03.5 (5123456)|EXECUTION_STARTED
11:42:03.5 (5189012)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
11:42:03.5 (7345678)|USER_DEBUG|[1]|DEBUG|Hello, Ada!
11:42:03.5 (7456789)|CODE_UNIT_FINISHED|execute_anonymous_apex
11:42:03.5 (7501234)|EXECUTION_FINISHEDExact timestamps, the API version, and the log levels differ in your output. Read it in three parts.
- Status lines.
Compiled successfullyandExecuted successfullyreport the two phases. A failure in either phase stops the run and prints the problem instead. - Header line. The line beginning with the API version lists the categories and levels that were active.
- Event lines. Each line has a timestamp, an event name, and details.
USER_DEBUGevents come from yourSystem.debugcalls. The[1]is the line number in your code, andDEBUGis the level you passed (the default).
To find your own output quickly, filter the Output panel text for USER_DEBUG.
Compile errors and runtime errors
The two phases fail in different ways.
| Phase | Typical cause | What you see |
|---|---|---|
| Compile | Typo, missing class, wrong method signature | `Compilation failed` with a line and column number |
| Runtime | Null reference, DML failure, governor limit | `Executed with errors` or an `EXCEPTION_THROWN` and `FATAL_ERROR` event in the log |
Line numbers in a compile error refer to the snippet you submitted, not to a class in your project. Anonymous code that comes from a selection is numbered from its first selected line.
How debug logs are produced
An anonymous run writes a log only if the running user has logging enabled at some level. The CLI usually requests a log for you when it executes anonymous Apex, which is why you see output right away. Logs from other activity, such as running tests or a user action in the browser, depend on a trace flag.
A trace flag is a record in the org that tells Salesforce to log activity for a user, a class, or a trigger, for a limited time window. It points at a debug level, which is a record that sets how much detail each category records.
- Category is an area of behavior, such as
Apex Code,Database,Workflow,Validation, orSystem. - Level is the verbosity for that category, from
NONEandERRORup throughWARN,INFO,DEBUG,FINE,FINER, andFINEST.
Higher levels record more events and produce larger logs. Each log is capped at 20 MB. When the limit is reached, Salesforce truncates the log, so the lines you need can be missing. An org also has a total log storage limit. Old logs are deleted when the limit is reached, and trace flags that cannot write new logs can stop working until space is freed.
Controlling log detail from VS Code
The extensions can create and manage trace flags for you.
- Run SFDX: Turn On Apex Debug Log for Replay Debugger from the Command Palette. This creates a trace flag for your user and a debug level named
ReplayDebuggerLevels. That debug level records at the detail the Replay Debugger needs. - Run your anonymous snippet or tests.
- When you finish, run SFDX: Turn Off Apex Debug Log for Replay Debugger. This deletes the trace flag and the debug level that the command created.
The trace flag expires on its own after a period, so a long session may need you to turn logging on again. If logs stop appearing mid-session, an expired flag is the first thing to check.
You can see the same flags in the org under Setup > Debug Logs. The page lists active trace flags and the logs they produced.
Working with logs after the run
Anonymous runs show their log immediately, but you often want logs from other activity too.
- SFDX: Get Apex Debug Logs lists the recent logs in the org and lets you choose one. The extension downloads it into
.sfdx/tools/debug/logsin your project and opens it. - List logs with the CLI:
sf apex list log- Download a specific log by ID:
sf apex get log --log-id 07LXXXXXXXXXXXXXXX --output-dir logsReplace the ID with one from the list. The --output-dir flag writes a file for each log, which is useful for searching with other tools. Keep the directory out of version control by adding it to .gitignore.
- Stream logs as they happen:
sf apex tail log --colorThis keeps the terminal open and prints new log lines as they arrive. Use it when you trigger Apex from the browser and want to watch it live. Stop it with Ctrl+C.
Writing useful debug statements
A log is only as useful as the statements you put in it. A few habits help.
Account acc = new Account(Name = 'Acme');
System.debug(LoggingLevel.INFO, 'Before insert: ' + acc);
insert acc;
System.debug(LoggingLevel.INFO, 'After insert, Id = ' + acc.Id);- Pass a
LoggingLevelso you can choose to record the line or not, based on the level in the debug level. - Include a label and the value, not just the value.
- Avoid logging inside large loops. Each iteration adds lines, and the log can reach the size cap before the part you care about.
This snippet inserts a real record. Run it in a sandbox or Developer Edition org, and delete the record afterward.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| The command is missing from the Command Palette | The Salesforce extensions are not active, or no DX project folder is open | Open the project folder itself, not a parent folder, and reload the window |
| `No default org` or an authorization error | The default org is unset, or its token expired | Re-run `sf org login web --alias my-org --set-default` |
| `Variable does not exist` | The class is not in the org | Deploy the source, then run again |
| Run succeeds but the log has no `USER_DEBUG` lines | The `Apex Code` level is above `DEBUG`, or the log was truncated | Lower the level threshold for that category, or reduce other logging |
| Logs stop appearing | The trace flag expired | Run the turn-on command again |
| The log is cut off | It reached the 20 MB cap | Use a less detailed level, and log less in loops |
Summary of commands
| Task | VS Code command | CLI equivalent |
|---|---|---|
| Run the whole file | SFDX: Execute Anonymous Apex with Editor Contents | `sf apex run --file <path>` |
| Run selected text | SFDX: Execute Anonymous Apex with Currently Selected Text | none |
| Turn on logging for replay | SFDX: Turn On Apex Debug Log for Replay Debugger | none |
| Fetch a log | SFDX: Get Apex Debug Logs | `sf apex get log` |
| Watch logs live | none | `sf apex tail log` |
Exercise
You run System.debug(GreetingService.greet('Ada')); as anonymous Apex and the output says Compilation failed with the message Variable does not exist: GreetingService. Why did this happen, and what do you do?
Show answer
Anonymous Apex runs in the org, so it can only call classes that already exist there. GreetingService has not been deployed to the default org (or the default org is a different org than you expect). Check the org name in the status bar, deploy force-app with sf project deploy start --source-dir force-app, and run the snippet again.
Exercise
A run reports Executed successfully, but you cannot find your message in the log. Name two possible causes and how to check each.
Show answer
First, the log may have been truncated at the 20 MB cap, which you can check by looking at the log size and whether it ends abruptly. Second, the debug level for the Apex Code category may be set above DEBUG, so System.debug lines at the default level are not recorded. Check the header line of the log, which lists the active categories and levels, and adjust the debug level.