Why Am I Getting Errors When Creating a TraceFlag with Apex?

Why Am I Getting Errors When Creating a TraceFlag with Apex?

On December 10, 2025, Posted by , In Uncategorized, With Comments Off on Why Am I Getting Errors When Creating a TraceFlag with Apex?
TraceFlag creation error in Apex

When you try to create a TraceFlag record from Apex using the Tooling API, you can run into two common errors: HTTP 400 Bad Request and “insufficient access rights on cross-reference id”. These errors almost always relate to permissions, missing required fields, or using the wrong DebugLevel record. Below is a clear explanation of why they occur and how to fix them.

Answer

Creating a TraceFlag from Apex requires calling the Tooling API endpoint with JSON-formatted data and a valid session ID. The TraceFlag object has several required fields such as TracedEntityId, LogType, DebugLevelId, StartDate, and ExpirationDate.

Initially, your request was failing with a 400 Bad Request error. That usually happens when the JSON structure is incorrect, a required field is missing, or the endpoint URL is malformed. You corrected this by removing trailing spaces, properly serializing your JSON, and including a valid DebugLevelId.

Once the DebugLevelId was added, the next error appeared:

insufficient access rights on cross-reference id: 7dl160000008OKa

This error indicates that the running user does not have permission to reference the DebugLevel record. In Salesforce, DebugLevel records are special metadata objects stored in the Tooling API. Normal users typically do not have access to read or use them. If your Invocable Apex is running in an Experience Cloud context, your options are even more limited.

There are two main reasons for this error:

1. The DebugLevel record belongs to another user or to the “Automated Process” user

TraceFlags and DebugLevels are user-scoped, and you can only reference a DebugLevel that you own or have visibility to. If the DebugLevel you are referencing was created by a system user, you will get a cross-reference access error.

2. The running context does not have API or Tooling API access

Experience Cloud users cannot use the Tooling API. Even internal users running a Flow’s Invocable Apex will fail if:

  • They lack Modify All Data.
  • They lack Author Apex or View All Data (indirectly required).
  • They do not have access to the DebugLevel metadata.

This means your Apex can run perfectly in Developer Console but fail in a Flow or Experience Cloud.

Corrected and Recommended Version of Your Code

Below is your code, cleaned up and annotated:

global without sharing class StartTraceCurrentUser {
    @InvocableMethod(label='Start User Trace' description='Starts one-hour current user debug trace')
    public static void StartLog() {

        HttpRequest req = new HttpRequest();
        req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
        req.setHeader('Content-Type', 'application/json');   
        req.setEndpoint(Url.getOrgDomainUrl().toExternalForm() + '/services/data/v61.0/tooling/sobjects/TraceFlag/');

        Map<String, String> traceflag = new Map<String, String>();
        traceflag.put('TracedEntityId', UserInfo.getUserId());
        traceflag.put('StartDate', Datetime.now().formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''));
        traceflag.put('ExpirationDate', Datetime.now().addMinutes(60).formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''));
        traceflag.put('DebugLevelId', '7dl160000008OKaAAM');  // must be accessible!
        traceflag.put('LogType', 'USER_DEBUG');

        String reqBody = JSON.serialize(traceflag);
        req.setBody(reqBody);
        req.setMethod('POST'); 

        try {
            Http http = new Http();
            HttpResponse res = http.send(req);
            System.debug('Response: ' + res.getBody());
        } catch (Exception e) {
            System.debug('Post Error: ' + e.getMessage());
        }
    }
}

How to Fix the “Insufficient Access Rights on Cross-Reference Id” Error

There are several possible fixes for this:

Fix 1: Create the DebugLevel dynamically from Apex first

You can avoid permissions issues by creating the DebugLevel within the same code execution. Then you own the record and can reference it.

HttpRequest dlReq = new HttpRequest();
dlReq.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
dlReq.setHeader('Content-Type', 'application/json');
dlReq.setEndpoint(Url.getOrgDomainUrl().toExternalForm() + '/services/data/v61.0/tooling/sobjects/DebugLevel/');

Map<String, String> dl = new Map<String, String>();
dl.put('DeveloperName', 'DynamicDebugLevel_' + Datetime.now().getTime());
dl.put('ApexCode', 'DEBUG');
dl.put('Workflow', 'DEBUG');
dl.put('Database', 'DEBUG');
dl.put('System', 'DEBUG');
dl.put('Callout', 'DEBUG');
dl.put('ApexProfiling', 'INFO');

dlReq.setBody(JSON.serialize(dl));
dlReq.setMethod('POST');

Http dlHttp = new Http();
HttpResponse dlRes = dlHttp.send(dlReq);

String debugLevelId = (String) JSON.deserializeUntyped(dlRes.getBody())['id'];

Now use debugLevelId in your TraceFlag.

This method is the most reliable and avoids cross-reference ID issues.

Fix 2: Store the DebugLevelId in a Custom Metadata or Custom Setting that admins maintain

This only works if the DebugLevel is:

  • Visible to the running user.
  • Not owned by a restricted system user.

In most cases this still fails in Experience Cloud.

Fix 3: Run the Apex in a System Context with Modify All Data

For example:

  • An Apex class marked without sharing (you already have this)
  • A Flow that runs as System Context
  • A Scheduled Job
  • An Apex REST service called internally

However, Tooling API still enforces additional internal restrictions, so this may or may not work depending on the org.

Final Recommendation

The safest and most reliable approach is:

Create the DebugLevel dynamically in Apex; then create the TraceFlag using the same user session.

This guarantees correct ownership and avoids cross-reference access errors.

Enroll for Career-Building Salesforce Training with Real-Time Projects

Our Salesforce Course is meticulously designed to offer an in-depth understanding of the Salesforce platform, providing you with the crucial skills needed to excel in the CRM domain. The program includes essential modules like Salesforce Admin, Developer, and AI, integrating foundational theory with practical, hands-on experience. By engaging in live projects and real-world assignments, you’ll develop the expertise to solve complex business challenges with confidence, using Salesforce solutions. Our experienced instructors ensure you acquire both technical knowledge and valuable industry insights, enabling you to thrive in the Salesforce ecosystem.

In addition to mastering technical concepts, our Salesforce Training in Thiruvananthapuram offers personalized mentorship, exam preparation, and interview coaching to boost your career prospects. You’ll have access to comprehensive study materials, practical project experience, and consistent support throughout your learning journey. Upon completion, you’ll be fully prepared for certification exams and equipped with the practical problem-solving skills employers highly value. Embark on your Salesforce career with us—Sign up for a Free Demo today!

Comments are closed.