How to Fix TraceFlag Creation Errors in Apex?

How to Fix TraceFlag Creation Errors in Apex?

On April 19, 2025, Posted by , In Apex, With Comments Off on How to Fix TraceFlag Creation Errors in Apex?
How to Fix TraceFlag Creation Errors in Apex?

Question:

I am attempting to create a TraceFlag from Invocable Apex to debug an Experience Cloud screen flow. The initial issue was a “Bad Request” error (Status Code 400). After some debugging, I learned that the DebugLevelId field is required for TraceFlag creation, and not specifying individual debug level settings like ApexCode or Database is acceptable. I added the DebugLevelId, but now I encounter the error: “insufficient access rights on cross-reference id,” with the ID being the DebugLevel I am trying to use.

Here is the code I am working with:

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');
        traceflag.put('LogType', 'USER_DEBUG');

        String reqBody = JSON.serialize(traceflag);
        System.debug(reqBody);

        req.setBody(reqBody);
        req.setMethod('POST');

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

What causes the “insufficient access rights on cross-reference id” error, and how can I resolve this issue? Are there alternative methods to create TraceFlags if this approach fails?

Answer:

The error “insufficient access rights on cross-reference id” occurs because the DebugLevelId you are using belongs to another user or is not accessible to the current user due to sharing settings or ownership. Here are ways to resolve this issue:

CRS Info Solutions provides Salesforce training in Singapore with real-time projects, certification guidance, interview prep, and practical job-ready skills.

1.Verify DebugLevel Accessibility:

Ensure the DebugLevelId belongs to a DebugLevel that the current user can access. DebugLevels are associated with specific users or org-wide settings. Use the Tooling API to query existing DebugLevels:

SELECT Id, DeveloperName, MasterLabel FROM DebugLevel

Code explanation:
The query SELECT Id, DeveloperName, MasterLabel FROM DebugLevel retrieves the Id, DeveloperName, and MasterLabel fields of all DebugLevel records in the org using the Tooling API, allowing you to view or reference existing debug levels for creating or updating TraceFlags.

2.Create a New DebugLevel:

If you do not have access to a suitable DebugLevel, create a new one programmatically or through the Developer Console:

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/DebugLevel/');
req.setMethod('POST');
req.setBody(JSON.serialize(new Map<String, String>{
    'DeveloperName' => 'CustomDebugLevel',
    'MasterLabel' => 'CustomDebugLevel',
    'ApexCode' => 'DEBUG',
    'Workflow' => 'DEBUG'
}));
HttpResponse res = new Http().send(req);
System.debug(res.getBody());

Code explanation:
This code creates a new DebugLevel record in Salesforce using the Tooling API. It constructs an HTTP POST request with the required headers, endpoint, and a JSON body containing fields like DeveloperName, MasterLabel, ApexCode, and Workflow, then sends the request and logs the response to debug the result.

3.Assign the Correct DebugLevelId:

Use the newly created DebugLevel ID in the DebugLevelId field of your TraceFlag request.

4.Check User Permissions:

Ensure the user initiating the request has the necessary permissions to create TraceFlags. They need the “Modify All Data” or “Author Apex” permission.

5.Use System Admin Context:

If your Apex class runs without sharing, ensure it operates with sufficient privileges to access the DebugLevel and create the TraceFlag.

If all else fails, consider creating TraceFlags directly through the Developer Console or Salesforce Setup for a quicker debugging solution. This avoids potential issues with Tooling API access and permissions.

Summing Up:

Creating a TraceFlag programmatically in Salesforce using Apex involves setting up an HTTP request to the Tooling API with the necessary headers, endpoint, and JSON body. The process requires specifying a valid DebugLevelId, which can be queried or created dynamically if not available. Issues like “insufficient access rights on cross-reference id” often arise due to permissions or ownership conflicts with the referenced DebugLevel, highlighting the importance of ensuring accessibility and proper privileges for the user initiating the request. By combining thoughtful debugging, proper Tooling API usage, and attention to permissions, you can effectively create and manage TraceFlags to facilitate debugging and monitoring in your Salesforce org.

Boost Your Career with Expert Salesforce Training in Singapore

Take your professional growth to the next level with CRS Info Solutions’ top-tier Salesforce training in Singapore. Our comprehensive courses are designed to equip you with the knowledge and practical skills necessary to excel in the dynamic Salesforce ecosystem. From Salesforce Admin and Developer to AI-focused modules, our curriculum combines in-depth theoretical learning with hands-on project experience, ensuring you’re prepared for real-world challenges.

Whether you’re just starting or looking to enhance your expertise, our carefully structured program will help you master the essential tools and techniques for success. Benefit from personalized mentorship, access to detailed study materials, and expert-led certification prep to confidently navigate interviews and job opportunities.

Join our free demo class today and take the first step towards a successful Salesforce career! Enroll now to secure your spot!!!

Comments are closed.