I'm just tired of manually setting trace flags on my org.

My question is, is it possible in any way to create trace flags using SFDX? Or is there any APEX script to create these trace flags for certain user?


1 Answer 1


Yes, you can create a Trace Flag via command line.

The command for creating a new Trace Flag:

sfdx force:data:record:create --sobjecttype TraceFlag -v "StartDate=$NOW ExpirationDate=$EXP TracedEntityId=$TRACE_ID LogType=USER_DEBUG DebugLevelId=$DEBUG_LEVEL_ID" --usetoolingapi

Extending an existing Trace Flag:

sfdx force:data:record:update --sobjecttype TraceFlag --sobjectid $TRACEID -v "StartDate=$NOW ExpirationDate=$EXP" --usetoolingapi --json --loglevel fatal

These were just the basic commands. If you build a script around it you can do much more.

For example, the following PowerShell script extends an existing trace flag on the Automated Process User.

#!/usr/bin/env pwsh

#Get User Id of Automated Process User
$USERID=(sfdx force:data:soql:query -q "SELECT Id, Name FROM User WHERE Name = 'Automated Process' AND CompanyName = 'Salesforce Architect'" --json | ConvertFrom-Json -AsHashtable)["result"]["records"][0]["Id"]

#Get existing Trace Flag
enter code here
$EXISTING_TRACE_QUERY=(sfdx force:data:soql:query --query "SELECT Id, DebugLevel.DeveloperName, ExpirationDate, TracedEntityId FROM Traceflag WHERE TracedEntityId IN (SELECT ID from USER WHERE ID = '${USERID}')" --usetoolingapi --json | ConvertFrom-Json -AsHashtable)

#New StarDate and ExpirationDate
$EXP=($NOW | Get-Date).AddHours(3) | Get-Date -Format "yyyy-MM-ddTHH:mm:ss"

#Update trace flag and extend by 3 hours
sfdx force:data:record:update --sobjecttype TraceFlag --sobjectid $TRACEID -v "StartDate=$NOW ExpirationDate=$EXP" --usetoolingapi --json --loglevel fatal

Documentation on CLI: https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_reference.meta/sfdx_cli_reference/cli_reference_force_data.htm

  • 1
    sfdx is being deprecated, as well as two of the command flags used in this answer (--sobjectype & --usetoolingapi). As of the end of September 2023, the command should look more like: sf force data record create --use-tooling-api --sobject TraceFlag....
    – Moonpie
    Sep 29, 2023 at 15:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .