function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shabu Thomas 12Shabu Thomas 12 

Debug log not created after dynamic creation of user trace flag

I ma developing a personal application. In it, my code is doing the following:
- Create a debug log level, if it is not there. If it is there, fetch it
- Create a user trace flag with the above debug log level, if it is not for logged in user. If it is there, reset the start and end time
- use system.debug in many places

So, my expectation is that a user trace flag will be automatically created or reset, when this code is executed.
The first two steps are being executed successfully.


For the first time, that is, when the user trace flag will be created, no debug log will be generated. But for the subsequent executions, debug logs will be created as the user trace flag is already there.

That, I observed that no debug logs will be generated in a transaction for a user trace flag, if that user trace flag is dynamically created in same transaction. Is there any way to overcome this issue?

Thanks in advance.
Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
Hello Shabu,

I believe there is not an easy way to achieve what you are looking for. As you mentioned, the fact that the created trace flag is within the same transaction where you have System.debug statements prevents Salesforce from printing them.

The only workaround I can imagine is trying to isolate the transaction that checks and upsert the trace flags from the code with System.debug statements.

Hope to have helped!


Don't forget to mark your thread as 'SOLVED' with the answer that best helps you.
Shabu Thomas 12Shabu Thomas 12
Hi Zuinglio,

Thanks for the comment. I have already thought about setting user trace flag and writing debug logs as different transactions. I have put the first one in a future method. But, when writing debug log, we can not make sure that trace flag has been created or not. I have thought about pushing the debug log writing to queues. But it has two limitations. 
-- I cant write more than 50 logs
-- debug log file will be created for each debug log statement

So, my current plan is to write the logs in a custom object for firsr transation as there is no problem for the subsequent ones. If we can fire user trigger in on user login, I would have solved this issue easily. 😀
Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
Hello Shabu,

I do agree with you. I hope you manage to find the best solution. You still have the option to create a Custom Login Flow, this would allow you to set the trace flag when any user logs in.