6

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?

2

1 Answer 1

7

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

The command for creating a new Trace Flag:

sf data create record --sobject TraceFlag -v "StartDate=$NOW ExpirationDate=$EXP TracedEntityId=$TRACE_ID LogType=USER_DEBUG DebugLevelId=$DEBUG_LEVEL_ID" --use-tooling-api

Extending an existing Trace Flag:

sf data update record --sobject TraceFlag --record-id $TRACEID -v "StartDate=$NOW ExpirationDate=$EXP" --use-tooling-api --json

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=(sf data query --query "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=(sf data query --query "SELECT Id, DebugLevel.DeveloperName, ExpirationDate, TracedEntityId FROM Traceflag WHERE TracedEntityId IN (SELECT ID from USER WHERE ID = '${USERID}')" --use-tooling-api --json | ConvertFrom-Json -AsHashtable)
$TRACEID=$EXISTING_TRACE_QUERY["result"]["records"][0]["Id"]

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

#Update trace flag and extend by 3 hours
sf data update record --sobject TraceFlag --record-id $TRACEID -v "StartDate=$NOW ExpirationDate=$EXP" --use-tooling-api --json

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

1
  • 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
    Commented 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 .