Developer Console Basics

Get Started with the Developer Console

Name several uses for the Developer Console. Decide whether to use the Developer Console or a different developer tool. Set up workspaces to organize your tabs.
  • What is the Developer Console?
    • An Integrated Development Environment (IE, an IED) where you can create, debug, and test apps in your org
    • One-stop solution for a variety of development tasks:
      • Navigate, open, create, edit Apex classes and triggers, Aura components, Visualforce pages and components
      • Browse packages that you’ve created in your org
      • Generate logs for debugging, analyze them from different perspectives
      • Test Apex code to ensure it’s error free
      • Identify and resolve errors by setting Checkpoints in Apex code
      • Write and execute SOQL and SOSL queries to find, create, update records in your org
  • When do you use the Developer Console?
    • 3 options to control a Salesforce org:
      • Third-party developer tools
      • Developer Console is connected to one org and browser-based
        • Best if you want changes to be effective immediately and don’t want to install anything
        • Be careful when using Developer Console in orgs you share with your teammates - no version control or conflict resolution
      • Salesforce Extensions for Visual Studio Code
        • Best if you want to connect to multiple orgs, compare or synchronize files, or use version control

  • Accessing the Developer Console
    • Access the developer console from the quick access menu (cog icon), then Developer Console
    • Two sections or panes:
      • Top: “source code editor”
      • Bottom: “tabs pane,” where you can view logs, errors, other information, and write queries to interact with the records in your org
  • What is a Workspace?
    • A workspace is just a collection of resources, represented by tabs, in the main panel of the Developer console
      • Create a workspace for any group of resources that you use together
      • Ex: you can have the related code, tests, and logs open for two different projects open simultaneously in separate workspaces
      • Workspaces reduce clutter and make it easier to navigate between different resources
  • Set up your own Workspace

Create an Apex class. Execute Apex code. Create a Lightning component. Create a Visualforce page.
  • Create an Apex Class
    • Apex is a strongly typed, object-oriented language that allows developers to execute flow and transaction-control statements on the Lightning Platform server in conjunction with calls to the Lightning Platform APIs
      • Looks a lot like Java code and interacts with the data in your org
    • Create a new Apex class via: File > New > Apex Class
    • Open an existing Apex class using: File > Open
    • The following class is presented in the trailhead
public class EmailMissionSpecialist {
   // Public method
   public void sendMail(String address, String subject, String body) {
      // Create an email message object
      Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
      String[] toAddresses = new String[] {address};
      mail.setToAddresses(toAddresses);
      mail.setSubject(subject);
      mail.setPlainTextBody(body);
      // Pass this email message to the built-in sendEmail method 
      // of the Messaging class
      Messaging.SendEmailResult[] results = Messaging.sendEmail(
                                new Messaging.SingleEmailMessage[] { mail });
      // Call a helper method to inspect the returned results
      inspectResults(results);
   }
   // Helper method
   private static Boolean inspectResults(Messaging.SendEmailResult[] results) {
      Boolean sendResult = true;
      // sendEmail returns an array of result objects.
      // Iterate through the list to inspect results. 
      // In this class, the methods send only one email, 
      // so we should have only one result.
      for (Messaging.SendEmailResult res : results) {
         if (res.isSuccess()) {
            System.debug('Email sent successfully');
         }
         else {
            sendResult = false;
            System.debug('The following errors occurred: ' + res.getErrors());                 
         }
      }
      return sendResult;
   }
}
  • Execute an Apex Class
    • Execute Anonymous is a feature that lets you test code and its results in real time
      • Note that any code run this way affects your org - any data deleted here is also deleted in the database
      • Open via: Debug > Open Execute Anonymous Window
      • Following code is example code that could be run in an execute anonymous window to run the code above
EmailMissionSpecialist em = new EmailMissionSpecialist();
em.sendMail('Enter your email address', 'Flight Path Change', 
   'Mission Control 123: Your flight path has been changed to avoid collision '
   + 'with asteroid 2014 QO441.');
  • What are Lightning Components?
    • Lightning Components is a framework for developing mobile and desktop apps
    • Can be used to create responsive user interfaces for Lightning Platform apps
    • Developer Console can be used to create a component bundle, which acts like a folder in that it contains components and all other related resources, such as style sheets, controllers, and design
  • Create an Aura Component
    • Create a new Aura component with File > New > Lightning Component
    • Example Aura component code shown below
  • To open an existing saved Aura component with any of the resources shown in the screen shot below, use File > Open Lightning Resources
<aura:component >
    <p>Greetings, fellow humans! What’s your status?</p>
</aura:component>

  • Create Visualforce Pages and Components
    • Visualforce is a web development framework for building sophisticated user interfaces for mobile and desktop apps
      • Visualforce is page-centric - when you save a record, the page interacts with the server and reloads the UI
      • Lightning components framework does more work on-device
  • Create a Visualforce Page
    • Create a new Visualforce page via: File > New > Visualforce Page
      • The Visualforce code below is included in the Trailhead
      • After saving, preview the Visualforce by clicking the “Preview” button in the top left
<apex:page sidebar="false">
    <!--Flight Systems Checklist Visualforce Page-->
    <h1>Checklist</h1>
    <apex:form id="engineReadinessChecklist">
        <apex:pageBlock title="Flight Systems Checklist">
            <!--First Section-->
            <apex:pageBlockSection title="Engines">
                <!--Adding Checkboxes-->
                <apex:inputCheckbox immediate="true"/>Engine 1
                <apex:inputCheckbox immediate="true"/>Engine 2
                <apex:inputCheckbox immediate="true"/>Engine 3
                <apex:inputCheckbox immediate="true"/>Engine 4
                <apex:inputCheckbox immediate="true"/>Engine 5
                <apex:inputCheckbox immediate="true"/>Engine 6
            </apex:pageBlockSection>
            <!--Second Section-->
            <apex:pageBlockSection title="Fuel Tanks">
                <apex:inputCheckbox immediate="true"/>Tank 1
                <apex:inputCheckbox immediate="true"/>Tank 2
                <apex:inputCheckbox immediate="true"/>Tank 3
                <apex:inputCheckbox immediate="true"/>Tank 4
                <apex:inputCheckbox immediate="true"/>Tank 5
                <apex:inputCheckbox immediate="true"/>Tank 6
            </apex:pageBlockSection>
            <apex:pageBlockButtons>
                <!--Adding Save Button-->
                <apex:commandButton value="Save" action="{!save}"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Generate and Analyze Logs

View debug logs in the Log Inspector or a text editor. Set various log levels for your debug logs. Manage and switch perspectives using the Log Inspector.
  • View Debug Logs
    • Logs are one of the best places to identify problems with a system or program
    • The developer console lets you look at various debug logs to understand how code works and identify any performance issues
  • View Logs in the Text Editor
    • Two ways to view a log:
      1. Before execution, enable open log in the Enter Apex Code window
        • Select Debug > Open Execute Anonymous Window, then check the Open Log checkbox
        • After execution, double-click the log that appears in the Logs tab
      2. After execution, double-click the log that appears in the Logs tab

Sample code that can be used in Execute Anonymous windows:

EmailMissionSpecialist em = new EmailMissionSpecialist();
em.sendMail('Enter your email address', 'Flight Path Change', 
   'Mission Control 123: Your flight path has been changed to avoid collision '
   + 'with asteroid 2014 QO441.');

  • Read Your Log Data
    • Debug Logs contain the following columns:
      • Timestamp: time when the event occurred. Always in the user’s time zone and HH:mm:ss:SSS format
      • Event: event that triggered the debug log entry, ex: HEAP_ALLOCATE, CODE_UNIT_STARTED, METHOD_ENTRY, METHOD_EXIT, etc
      • Details: details about the line of code and method name where the code was executed
    • Filter the entries in the Execution Log by checking certain checkboxes: This Frame, Executable, Debug Only, and Filter
    • Can also view debug log as a “raw log”, which shows more information. Examples shown below.

  • System.debug allows you to write values directly into the log. Here’s syntax:
    • System.debug('Your Message');
    • System.debug(yourVariable);
    • System.debug('Your Label: ' + yourVariable);
  • Use the Log Inspector
    • Log Inspector exists to make it easier to view large logs. Enable with Debug > View Log Panels
      1. Stack Tree: displays log entries within the hierarchy of their objects and their execution using a top-down tree view.
      • Execution Stack: bottom-up view of the selected item. Displays the log entry followed by the operation that called it.
      • Execution Log: displays every action that occurred during execution of your code
      • Source: displays the contents of the source file, indicating the line of code being run when the log was generated
      • Source List: displays the context of the code being executed
      • Variables: displays the variables and their assigned values that were ins cope when the code that generated the selected log entry was run
      • Execution Overview: displays statistics for the code being executed, including execution time and heap size
  • What is the Perspective Manager and how can you switch Perspectives?
    • Perspectives are layouts of grouped panels:
      • “Debug” perspective displays the Execution Log, Source, and Variables
      • “Analysis” perspective displays the Stack Tree, Execution Log, Execution Stack, and Execution Overview
    • New Perspectives can be saved, and you can switch between the different available perspectives

  • Log Categories
    • Log Categories is the type of information that is being logged. Two common examples:
      • ApexCode: logs events related to Apex code and includes info about the start and end of an Apex method
      • Database: includes logs related to database events including DML as well as SOSL and SOQL queries
  • Log Levels and how to Change them?
    • Log levels control how much detail is logged for each log category, from NONE, ERROR, WARN, INFO, DEBUG, FINE, FINER, FINEST
    • Log levels are cumulative, so INFO includes log info from ERROR and WARN levels as well

Inspect Objects at Checkpoints

Set up checkpoints in your Apex code. Analyze the objects in memory using the Checkpoint Inspector.
  • Set Checkpoints in your Apex Code
    • Checkpoints show you snapshots of what’s happening in Apex code at particular points during execution
    • Up to five checkpoints allowed in Apex - Checkpoints aren’t available for Visualforce
    • Add a checkpoint by clicking to the left of the line number. A red dot will appear.

  • Checkpoints Tab
    • After adding a checkpoint and running code, you can open the debug log and click the Checkpoints tab to see the results

  • Checkpoints Inspector
    • Double-click a checkpoint inn the Checkpoints table to see the captured results in the Checkpoint Inspector
    • Two tabs available: Heap and Symbols
  • Heap Tab: displays all objects present in memory at the line of code where the checkpoint was executed
    • The Types area shows how many objects were instantiated and the memory they consumed in bytes
    • The Instances area shows the various instances of each Type in memory
    • The State area shows the object’s fields and their values

  • Symbols Tab: displays all symbols in memory in tree view
    • Quick and simple way to review the states of various objects at any checkpoint
    • Symbols are unique names that reference particular objects - this tab displays all symbols in memory using a tree view

Execute SOQL and SOSL Queries

Execute a SOQL query using the Query Editor or in Apex code. Execute a SOSL search using the Query Editor or in Apex code.
  • What is a SOQL Query?
    • SOQL stands for Salesforce Object Query Language and is syntatictally similar to SQL
    • Write and execute SOQL queries in Apex code or in the Developer Console’s Query Editor
  • Execute a SOQL Query
    • The following DML adds three contacts to Salesforce when run in an Execute Anonymous window
// Add first contact and related details
Contact contact1 = new Contact(
   Firstname='Quentin',
   Lastname='Foam',
   Phone='(415)555-1212',
   Department= 'Specialty Crisis Management',
   Title='Control Engineer - Specialty - Solar Arrays',
   Email='qfoam@trailhead.com');
insert contact1;
// Add second contact and related details
Contact contact2 = new Contact(
   Firstname='Vega',
   Lastname='North',
   Phone='(416)556-1312',
   Department= 'Specialty Crisis Management',
   Title='Control Engineer - Specialty - Propulsion',
   Email='vnorth@trailhead.com');
insert contact2;
// Add third contact and related details
Contact contact3 = new Contact(
   Firstname='Palma',
   Lastname='Sunrise',
   Phone='(554)623-1212',
   Department= 'Specialty Crisis Management',
   Title='Control Engineer - Specialty - Radiators',
   Email='psunrise@trailhead.com');
insert contact3;
  • The following queries against the three contacts just added to Salesforce
SELECT Name, Phone, Email, Title FROM Contact
                                 WHERE (Department = 'Specialty Crisis Management')

  • Running the following in an Execute Anonymous window prints the number of accounts returned and their contact details in alphabetical order
Contact[] theseContacts = [SELECT Name, Phone, Email, Description FROM Contact
                           WHERE (Department='Specialty Crisis Management')
                           ORDER BY Name];
// Log a count of how many contacts were found
System.debug(theseContacts.size() + ' contact(s) returned.');
// Log all values in the array of contacts
System.debug(theseContacts);
  • What is a SOSL Search?
    • SOSL is a language that performs text searches in records
    • SOSL can query multiple types of objects at the same time and uses a word match to match fields, whereas SOQL needs the exact phrase
  • Execute a SOSL Search
    • Notice that only the partial name of the department “Specialty Crisis Management” is included in the query
FIND {Crisis} IN ALL FIELDS RETURNING Contact(FirstName, LastName, Phone, Email, Title)

  • Running the following in an Execute Anonymous window also works similarly to the Apex-embedded SOQL query above
List<List<sObject>> searchList = [FIND 'Crisis' IN ALL FIELDS 
                                  RETURNING Contact(FirstName, LastName,
                                  Phone, Email, Description)];
Contact[] searchContacts = (Contact[])searchList[0];
System.debug('Found the following contacts:');
for (Contact c : searchContacts) {
   System.debug(c.LastName + ', ' + c.FirstName);
}