Do Apex Transaction have a unique Id (like Batch Ids)?

New, as of Winter 21 you can do this by calling

Request.getCurrent().getRequestId()

See https://releasenotes.docs.salesforce.com/en-us/winter21/release-notes/rn_apex_Runtime_Detection.htm

And https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_System_Request.htm


No. You could generate one yourself using UUID, or some other concept. But at least as far as is documented and what we can access, synchronous transactions do not have a job Id. If you look at Daniel Ballinger's post on obscure key prefixes, none seem a likely match, other than maybe SyncTransactionLog, which is not documented in the SOAP API Developer Guide.

If you want to use UUID, I'd take the code in this post and adapt it slightly.

public with sharing class UUID
{
    public static String generate()
    {
        String rawId = EncodingUtil.ConvertTohex(Crypto.GenerateAESKey(128));
        return String.join(new List<String> {
            rawId.subString(0,8),
            rawId.subString(8,12),
            rawId.subString(12,16),
            rawId.subString(16,20),
            rawId.substring(20)
        }, '-');
    }
}

Then you can just lazy load an Id in this class, but it would likely be more appropriate to set such a property in your TransactionLog class or similar.