-
-
Notifications
You must be signed in to change notification settings - Fork 232
Expand file tree
/
Copy pathLogEntryEventBuilder.cls
More file actions
1448 lines (1265 loc) · 65.2 KB
/
LogEntryEventBuilder.cls
File metadata and controls
1448 lines (1265 loc) · 65.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------------------------//
// This file is part of the Nebula Logger project, released under the MIT License. //
// See LICENSE file or go to https://github.com/jongpie/NebulaLogger for full license details. //
//------------------------------------------------------------------------------------------------//
/**
* @group Logger Engine
* @description Builder class that generates each `LogEntryEvent__e` record
* @see Logger
*/
@SuppressWarnings(
'PMD.AvoidGlobalModifier, PMD.CognitiveComplexity, PMD.CyclomaticComplexity, PMD.ExcessiveClassLength, PMD.ExcessivePublicCount, PMD.NcssTypeCount, PMD.PropertyNamingConventions, PMD.StdCyclomaticComplexity'
)
global with sharing class LogEntryEventBuilder {
public static final String ENTRY_SAVE_REASON_LOGGING_LEVEL_MET = 'Logging Level Met';
public static final String ENTRY_SAVE_REASON_OVERRIDE = 'Save Overridden';
private static final Map<String, String> CACHED_SOBJECT_NAME_TO_CLASSIFICATION = new Map<String, String>();
private static final Schema.User CURRENT_USER = new Schema.User(Id = System.UserInfo.getUserId(), ProfileId = System.UserInfo.getProfileId());
private static final String HTTP_HEADER_FORMAT = '{0}: {1}';
private static final String NEW_LINE_DELIMITER = '\n';
private static String cachedOrganizationEnvironmentType;
@TestVisible
private static Id networkId = System.Network.getNetworkId();
private final LogEntryEvent__e logEntryEvent;
private final System.LoggingLevel entryLoggingLevel;
private final String organizationEnvironmentType;
private final LoggerSettings__c userSettings;
@TestVisible
private String debugMessage = '';
private Boolean detailsAreSet = false;
private Boolean shouldSave;
private Set<String> tags = new Set<String>();
private Boolean tagDetailsAreSet = true;
private static final LoggerSObjectProxy.AuthSession CACHED_AUTH_SESSION_PROXY {
get {
if (CACHED_AUTH_SESSION_PROXY == null) {
CACHED_AUTH_SESSION_PROXY = LoggerEngineDataSelector.getInstance().getCachedAuthSessionProxy();
}
return CACHED_AUTH_SESSION_PROXY;
}
set;
}
private static final Map<String, LogEntryDataMaskRule__mdt> CACHED_DATA_MASK_RULES {
get {
if (CACHED_DATA_MASK_RULES == null) {
CACHED_DATA_MASK_RULES = loadDataMaskRules();
}
return CACHED_DATA_MASK_RULES;
}
set;
}
private static final LoggerSObjectProxy.Network CACHED_NETWORK_PROXY {
get {
if (CACHED_NETWORK_PROXY == null) {
CACHED_NETWORK_PROXY = LoggerEngineDataSelector.getInstance().getCachedNetworkProxy(networkId);
}
return CACHED_NETWORK_PROXY;
}
set;
}
private static final Schema.Organization CACHED_ORGANIZATION {
get {
if (CACHED_ORGANIZATION == null) {
CACHED_ORGANIZATION = LoggerEngineDataSelector.getInstance().getCachedOrganization();
}
return CACHED_ORGANIZATION;
}
set;
}
private static final TransactionLimits CACHED_TRANSACTION_LIMITS {
get {
if (CACHED_TRANSACTION_LIMITS == null) {
CACHED_TRANSACTION_LIMITS = new TransactionLimits();
}
return CACHED_TRANSACTION_LIMITS;
}
set;
}
private static final Schema.User CACHED_USER {
get {
if (CACHED_USER == null) {
CACHED_USER = LoggerEngineDataSelector.getInstance().getCachedUser();
}
return CACHED_USER;
}
set;
}
private static final String NAMESPACE_PREFIX {
get {
if (NAMESPACE_PREFIX == null) {
NAMESPACE_PREFIX = getNamespacePrefix();
}
return NAMESPACE_PREFIX;
}
set;
}
private static final Map<String, String> SOBJECT_SUFFIX_TO_CLASSIFICATION {
get {
if (SOBJECT_SUFFIX_TO_CLASSIFICATION == null) {
SOBJECT_SUFFIX_TO_CLASSIFICATION = getSObjectSuffixToClassification();
}
return SOBJECT_SUFFIX_TO_CLASSIFICATION;
}
set;
}
/**
* @description Used by `Logger` to instantiate a new instance of `LogEntryEventBuilder`
* @param userSettings The instance of `LoggerSettings__c` for the current to use to control any feature flags
* @param entryLoggingLevel The `LoggingLevel` value to use for the log entry
* @param shouldSave Indicates if the builder's instance of `LogEntryEvent__e` should be saved
*/
@SuppressWarnings('PMD.NcssConstructorCount')
public LogEntryEventBuilder(LoggerSettings__c userSettings, System.LoggingLevel entryLoggingLevel, Boolean shouldSave) {
this.shouldSave = shouldSave;
if (this.shouldSave()) {
this.userSettings = userSettings;
this.entryLoggingLevel = entryLoggingLevel;
this.logEntryEvent = getLogEntryEventTemplate(entryLoggingLevel);
this.setSaveReason();
this.setTimestamp(System.now());
}
}
/**
* @description Sets the log entry event's message field
* @param logMessage The instance of `LogMessage` to use to set the entry's message field
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setMessage(LogMessage logMessage) {
if (this.shouldSave() == false && System.Test.isRunningTest() == false || logMessage == null) {
return this;
}
return this.setMessage(logMessage.getMessage());
}
/**
* @description Sets the log entry event's message field
* @param message The string to use to set the entry's message field
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setMessage(String message) {
// To help with debugging unit tests, always run System.debug statement in a test context
if ((this.shouldSave() || System.Test.isRunningTest()) && this.logEntryEvent != null) {
TextFieldValueCleaner textCleaner = new TextFieldValueCleaner(this.userSettings, Schema.LogEntryEvent__e.Message__c, message);
this.logEntryEvent.Message__c = textCleaner.textValue;
this.logEntryEvent.MessageMasked__c = textCleaner.wasMasked;
this.logEntryEvent.MessageTruncated__c = textCleaner.wasTruncated;
this.logToApexDebug(message);
}
return this;
}
/**
* @description Sets the log entry event's exception fields
* @param apexException The instance of an `System.Exception` to use.
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setExceptionDetails(System.Exception apexException) {
if (this.shouldSave() == false || apexException == null) {
return this;
}
this.logEntryEvent.ExceptionMessage__c = LoggerDataStore.truncateFieldValue(Schema.LogEntryEvent__e.ExceptionMessage__c, apexException.getMessage());
this.logEntryEvent.ExceptionType__c = apexException.getTypeName();
LoggerStackTrace exceptionStackTrace = new LoggerStackTrace(apexException);
this.logEntryEvent.ExceptionLocation__c = exceptionStackTrace.Location;
this.logEntryEvent.ExceptionSourceActionName__c = exceptionStackTrace.Source?.ActionName;
this.logEntryEvent.ExceptionSourceApiName__c = exceptionStackTrace.Source?.ApiName;
this.logEntryEvent.ExceptionSourceMetadataType__c = exceptionStackTrace.Source?.MetadataType.name();
this.logEntryEvent.ExceptionStackTrace__c = LoggerDataStore.truncateFieldValue(
Schema.LogEntryEvent__e.ExceptionStackTrace__c,
exceptionStackTrace.ParsedStackTraceString
);
return this;
}
// Approval-result builder methods. All of these methods re-use the DatabaseResult* fields,
// since these are still sort of DML results, and at least at this time, it's not worth introducing
// brand new fields just for approval results.
/**
* @description Sets the log entry event's database operation result fields
* @param lockResult The instance of `Approval.LockResult` to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setApprovalResult(Approval.LockResult lockResult) {
return this.setDatabaseDetails(new List<Approval.LockResult>{ lockResult }, Approval.LockResult.class, lockResult?.getId());
}
/**
* @description Sets the log entry event's database operation result fields
* @param processResult The instance of `Approval.ProcessResult` to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setApprovalResult(Approval.ProcessResult processResult) {
return this.setDatabaseDetails(new List<Approval.ProcessResult>{ processResult }, Approval.ProcessResult.class, processResult?.getEntityId());
}
/**
* @description Sets the log entry event's database operation result fields
* @param unlockResult The instance of `Approval.UnlockResult` to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setApprovalResult(Approval.UnlockResult unlockResult) {
return this.setDatabaseDetails(new List<Approval.UnlockResult>{ unlockResult }, Approval.UnlockResult.class, unlockResult?.getId());
}
/**
* @description Sets the log entry event's database operation result fields
* @param lockResults The list of `Approval.LockResult` instances to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setApprovalResult(List<Approval.LockResult> lockResults) {
return this.setDatabaseDetails(lockResults, Approval.LockResult.class, null);
}
/**
* @description Sets the log entry event's database operation result fields
* @param processResults The list of `Approval.ProcessResult` instances to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setApprovalResult(List<Approval.ProcessResult> processResults) {
return this.setDatabaseDetails(processResults, Approval.ProcessResult.class, null);
}
/**
* @description Sets the log entry event's database operation result fields
* @param unlockResults The list of `Approval.UnlockResult` instances to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setApprovalResult(List<Approval.UnlockResult> unlockResults) {
return this.setDatabaseDetails(unlockResults, Approval.UnlockResult.class, null);
}
// DML-result builder methods. All* of the Result classes behave the same (*except Upsert)
// but Salesforce didn't bother to use an interface for the classes, so instead - overloads!
/**
* @description Sets the log entry event's database operation result fields
* @param databaseResult The instance of `Object` (generic Database Result) to log
* @param type The instance of `System.Type` that indicates the type of Database Result class to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(Object databaseResult, System.Type type) {
return this.setDatabaseDetails(new List<Object>{ databaseResult }, type, null);
}
/**
* @description Sets the log entry event's database operation result fields
* @param deleteResult The instance of `Database.DeleteResult` to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(Database.DeleteResult deleteResult) {
return this.setDatabaseDetails(new List<Database.DeleteResult>{ deleteResult }, Database.DeleteResult.class, deleteResult?.getId());
}
/**
* @description Sets the log entry event's database operation result fields
* @param emptyRecycleBinResult The instance of `Database.EmptyRecycleBinResult` to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(Database.EmptyRecycleBinResult emptyRecycleBinResult) {
return this.setDatabaseDetails(
new List<Database.EmptyRecycleBinResult>{ emptyRecycleBinResult },
Database.EmptyRecycleBinResult.class,
emptyRecycleBinResult?.getId()
);
}
/**
* @description Sets the log entry event's database operation result fields
* @param leadConvertResult The instance of `Database.LeadConvertResult` to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(Database.LeadConvertResult leadConvertResult) {
return this.setDatabaseDetails(new List<Database.LeadConvertResult>{ leadConvertResult }, Database.LeadConvertResult.class, leadConvertResult?.getLeadId());
}
/**
* @description Sets the log entry event's database operation result fields
* @param mergeResult The instance of `Database.MergeResult` to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(Database.MergeResult mergeResult) {
return this.setDatabaseDetails(new List<Database.MergeResult>{ mergeResult }, Database.MergeResult.class, mergeResult?.getId());
}
/**
* @description Sets the log entry event's database operation result fields
* @param saveResult The instance of `Database.SaveResult` to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(Database.SaveResult saveResult) {
return this.setDatabaseDetails(new List<Database.SaveResult>{ saveResult }, Database.SaveResult.class, saveResult?.getId());
}
/**
* @description Sets the log entry event's database operation result fields
* @param upsertResult The instance of `Database.UpsertResult` to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(Database.UpsertResult upsertResult) {
this.setDatabaseDetails(new List<Database.UpsertResult>{ upsertResult }, Database.UpsertResult.class, upsertResult?.getId());
if (upsertResult != null) {
String subtype = upsertResult.isCreated() ? 'Insert' : 'Update';
this.logEntryEvent.DatabaseResultType__c += '.' + subtype;
}
return this;
}
/**
* @description Sets the log entry event's database operation result fields
* @param undeleteResult The instance of `Database.UndeleteResult` to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(Database.UndeleteResult undeleteResult) {
return this.setDatabaseDetails(new List<Database.UndeleteResult>{ undeleteResult }, Database.UndeleteResult.class, undeleteResult?.getId());
}
/**
* @description Sets the log entry event's database operation result fields
* @param databaseResults The list of `Object` (generic Database Result) instances to log
* @param type The type of Database Result instances to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(List<Object> databaseResults, System.Type type) {
return this.setDatabaseDetails(databaseResults, type, null);
}
/**
* @description Sets the log entry event's database operation result fields
* @param deleteResults The list of `Database.DeleteResult` instances to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(List<Database.DeleteResult> deleteResults) {
return this.setDatabaseDetails(deleteResults, Database.DeleteResult.class, null);
}
/**
* @description Sets the log entry event's database operation result fields
* @param emptyRecycleBinResults The list of `Database.EmptyRecycleBinResult` instances to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(List<Database.EmptyRecycleBinResult> emptyRecycleBinResults) {
return this.setDatabaseDetails(emptyRecycleBinResults, Database.EmptyRecycleBinResult.class, null);
}
/**
* @description Sets the log entry event's database operation result fields
* @param leadConvertResults The list of `Database.LeadConvertResult`s to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(List<Database.LeadConvertResult> leadConvertResults) {
return this.setDatabaseDetails(leadConvertResults, Database.LeadConvertResult.class, null);
}
/**
* @description Sets the log entry event's database operation result fields
* @param mergeResults The list of `Database.MergeResult` instances to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(List<Database.MergeResult> mergeResults) {
return this.setDatabaseDetails(mergeResults, Database.MergeResult.class, null);
}
/**
* @description Sets the log entry event's database operation result fields
* @param saveResults The list of `Database.SaveResult` instances to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(List<Database.SaveResult> saveResults) {
return this.setDatabaseDetails(saveResults, Database.SaveResult.class, null);
}
/**
* @description Sets the log entry event's database operation result fields
* @param upsertResults The list of `Database.UpsertResult` instances to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(List<Database.UpsertResult> upsertResults) {
return this.setDatabaseDetails(upsertResults, Database.UpsertResult.class, null);
}
/**
* @description Sets the log entry event's database operation result fields
* @param undeleteResults The list of `Database.UndeleteResult` instances to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setDatabaseResult(List<Database.UndeleteResult> undeleteResults) {
return this.setDatabaseDetails(undeleteResults, Database.UndeleteResult.class, null);
}
/**
* @description Deprecated - use `setRecord(Id recordId)` instead
* @param recordId The id of the record to set.
* @return An instance of LogEntryEventBuilder with a record associated wit recordId.
*/
global LogEntryEventBuilder setRecordId(Id recordId) {
return this.setRecord(recordId);
}
/**
* @description Deprecated - use `setRecord(SObject record)` instead
* @param record the record to set.
* @return An instance of LogEntryEventBuilder with the given record.
*/
global LogEntryEventBuilder setRecordId(SObject record) {
return this.setRecord(record);
}
/**
* @description Sets the log entry event's record fields
* @param recordId The ID of the SObject record related to the entry
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setRecord(Id recordId) {
if (this.shouldSave() == false || String.isBlank(recordId)) {
return this;
}
this.logEntryEvent.RecordCollectionSize__c = 1;
this.logEntryEvent.RecordCollectionType__c = 'Single';
this.logEntryEvent.RecordId__c = recordId;
try {
Schema.SObjectType sobjectType = recordId?.getSObjectType();
this.logEntryEvent.RecordSObjectClassification__c = getSObjectClassification(sobjectType);
this.logEntryEvent.RecordSObjectType__c = sobjectType.toString();
} catch (System.SObjectException sobjectException) {
// Some SObject Types are considered template objects, such as CaseComment, AccountHistory,
// ContactHistory, etc, so calling Id.getSObjectType() does not work for some types of record IDs
if (sobjectException.getMessage().contains('Cannot locate Apex Type') == false) {
throw sobjectException;
}
}
return this;
}
/**
* @description Sets the log entry event's record fields
* @param record The `SObject` record related to the entry. The JSON of the record is automatically added to the entry
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setRecord(SObject record) {
if (this.shouldSave() == false) {
return this;
}
this.logEntryEvent.RecordCollectionSize__c = 1;
this.logEntryEvent.RecordCollectionType__c = 'Single';
TextFieldValueCleaner textCleaner = new TextFieldValueCleaner(
this.userSettings,
Schema.LogEntryEvent__e.RecordJson__c,
getJson(record, this.userSettings.IsRecordFieldStrippingEnabled__c)
);
this.logEntryEvent.RecordJson__c = textCleaner.textValue;
this.logEntryEvent.RecordJsonMasked__c = textCleaner.wasMasked;
this.logEntryEvent.RecordJsonTruncated__c = textCleaner.wasMasked;
if (record == null) {
this.logEntryEvent.RecordSObjectClassification__c = 'Unknown';
this.logEntryEvent.RecordSObjectType__c = 'Unknown';
} else {
this.logEntryEvent.RecordId__c = record.Id;
this.logEntryEvent.RecordSObjectClassification__c = getSObjectClassification(record.getSObjectType());
this.logEntryEvent.RecordSObjectType__c = record.getSObjectType().toString();
this.logEntryEvent.RecordSObjectTypeNamespace__c = getSObjectTypeNamespace(record.getSObjectType());
}
return this;
}
/**
* @description Sets the log entry event's record fields
* @param records The list of `SObject` records related to the entry. The JSON of the list is automatically added to the entry
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setRecord(List<SObject> records) {
if (this.shouldSave() == false) {
return this;
}
this.logEntryEvent.RecordCollectionSize__c = records?.size();
this.logEntryEvent.RecordCollectionType__c = 'List';
TextFieldValueCleaner textCleaner = new TextFieldValueCleaner(
this.userSettings,
Schema.LogEntryEvent__e.RecordJson__c,
getJson(records, this.userSettings.IsRecordFieldStrippingEnabled__c)
);
this.logEntryEvent.RecordJson__c = textCleaner.textValue;
this.logEntryEvent.RecordJsonMasked__c = textCleaner.wasMasked;
this.logEntryEvent.RecordJsonTruncated__c = textCleaner.wasTruncated;
Schema.SObjectType sobjectType = records?.getSObjectType();
if (sobjectType == null) {
this.logEntryEvent.RecordSObjectClassification__c = 'Unknown';
this.logEntryEvent.RecordSObjectType__c = 'Unknown';
} else {
this.logEntryEvent.RecordSObjectClassification__c = getSObjectClassification(sobjectType);
this.logEntryEvent.RecordSObjectType__c = sobjectType.toString();
this.logEntryEvent.RecordSObjectTypeNamespace__c = getSObjectTypeNamespace(sobjectType);
}
return this;
}
/**
* @description Sets the log entry event's record fields
* @param recordIdToRecord The map of `SObject` records related to the entry. The JSON of the map is automatically added to the entry
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setRecord(Map<Id, SObject> recordIdToRecord) {
if (this.shouldSave() == false) {
return this;
}
this.logEntryEvent.RecordCollectionSize__c = recordIdToRecord?.size();
this.logEntryEvent.RecordCollectionType__c = 'Map';
TextFieldValueCleaner textCleaner = new TextFieldValueCleaner(
this.userSettings,
Schema.LogEntryEvent__e.RecordJson__c,
getJson(recordIdToRecord, this.userSettings.IsRecordFieldStrippingEnabled__c)
);
this.logEntryEvent.RecordJson__c = textCleaner.textValue;
this.logEntryEvent.RecordJsonMasked__c = textCleaner.wasMasked;
this.logEntryEvent.RecordJsonTruncated__c = textCleaner.wasTruncated;
List<SObject> recordsList = recordIdToRecord?.values();
Schema.SObjectType sobjectType = recordIdToRecord?.size() > 0 ? recordsList.get(0)?.getSObjectType() : null;
if (sobjectType == null) {
this.logEntryEvent.RecordSObjectClassification__c = 'Unknown';
this.logEntryEvent.RecordSObjectType__c = 'Unknown';
} else {
this.logEntryEvent.RecordSObjectClassification__c = getSObjectClassification(sobjectType);
this.logEntryEvent.RecordSObjectType__c = sobjectType.toString();
this.logEntryEvent.RecordSObjectTypeNamespace__c = getSObjectTypeNamespace(sobjectType);
}
return this;
}
/**
* @description Sets the log entry event's record fields
* @param recordIds The Set of `SObject` records ids related to the entry. Will be converted to list and the JSON of the list is automatically added to the entry
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setRecord(System.Iterable<Id> recordIds) {
if (this.shouldSave() == false) {
return this;
}
List<SObject> records;
if (recordIds != null) {
records = new List<SObject>();
for (Id recordId : recordIds) {
records.add(recordId.getSObjectType().newSObject(recordId));
}
}
return this.setRecord(records);
}
/**
* @description Sets the log entry event's HTTP Request fields
* @param request The instance of `HttpRequest` to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setHttpRequestDetails(System.HttpRequest request) {
return this.setHttpRequestDetails(request, new List<String>());
}
/**
* @description Sets the log entry event's HTTP Request fields
* @param request The instance of `HttpRequest` to log
* @param headersToLog An instance of `List<String>` containing the header keys to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setHttpRequestDetails(System.HttpRequest request, List<String> headersToLog) {
if (this.shouldSave() == false || request == null) {
return this;
}
String formattedHeaderKeysString;
String formattedHeadersString;
if (headersToLog != null & headersToLog.isEmpty() == false) {
formattedHeaderKeysString = String.join(headersToLog, NEW_LINE_DELIMITER);
if (LoggerParameter.STORE_HTTP_REQUEST_HEADER_VALUES) {
List<String> headers = new List<String>();
for (String headerKey : headersToLog) {
headers.add(String.format(HTTP_HEADER_FORMAT, new List<String>{ headerKey, request.getHeader(headerKey) }));
}
formattedHeadersString = String.join(headers, NEW_LINE_DELIMITER);
}
}
TextFieldValueCleaner textCleaner = new TextFieldValueCleaner(this.userSettings, Schema.LogEntryEvent__e.HttpRequestBody__c, request.getBody());
this.logEntryEvent.HttpRequestBody__c = textCleaner.textValue;
this.logEntryEvent.HttpRequestBodyMasked__c = textCleaner.wasMasked;
this.logEntryEvent.HttpRequestBodyTruncated__c = textCleaner.wasTruncated;
this.logEntryEvent.HttpRequestCompressed__c = request.getCompressed();
this.logEntryEvent.HttpRequestEndpoint__c = LoggerDataStore.truncateFieldValue(Schema.LogEntryEvent__e.HttpRequestEndpoint__c, request.getEndpoint());
this.logEntryEvent.HttpRequestEndpointAddress__c = LoggerDataStore.truncateFieldValue(
Schema.LogEntryEvent__e.HttpRequestEndpointAddress__c,
request.getEndpoint()
);
this.logEntryEvent.HttpRequestHeaderKeys__c = formattedHeaderKeysString;
this.logEntryEvent.HttpRequestHeaders__c = LoggerDataStore.truncateFieldValue(Schema.LogEntryEvent__e.HttpRequestHeaders__c, formattedHeadersString);
this.logEntryEvent.HttpRequestMethod__c = request.getMethod();
return this;
}
/**
* @description Sets the log entry event's HTTP Response fields
* @param response The instance of `HttpResponse` to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setHttpResponseDetails(System.HttpResponse response) {
if (this.shouldSave() == false || response == null) {
return this;
}
String formattedHeadersString;
if (LoggerParameter.STORE_HTTP_RESPONSE_HEADER_VALUES) {
List<String> headers = new List<String>();
for (String headerKey : response.getHeaderKeys()) {
headers.add(String.format(HTTP_HEADER_FORMAT, new List<String>{ headerKey, response.getHeader(headerKey) }));
}
formattedHeadersString = String.join(headers, NEW_LINE_DELIMITER);
}
TextFieldValueCleaner textCleaner = new TextFieldValueCleaner(this.userSettings, Schema.LogEntryEvent__e.HttpResponseBody__c, response.getBody());
this.logEntryEvent.HttpResponseBody__c = textCleaner.textValue;
this.logEntryEvent.HttpResponseBodyMasked__c = textCleaner.wasMasked;
this.logEntryEvent.HttpResponseBodyTruncated__c = textCleaner.wasTruncated;
this.logEntryEvent.HttpResponseHeaderKeys__c = String.join(response.getHeaderKeys(), NEW_LINE_DELIMITER);
this.logEntryEvent.HttpResponseHeaders__c = LoggerDataStore.truncateFieldValue(Schema.LogEntryEvent__e.HttpResponseHeaders__c, formattedHeadersString);
this.logEntryEvent.HttpResponseStatus__c = response.getStatus();
this.logEntryEvent.HttpResponseStatusCode__c = response.getStatusCode();
return this;
}
/**
* @description Sets the log entry event's REST Request fields
* @param request The instance of `System.RestRequest` to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setRestRequestDetails(System.RestRequest request) {
if (this.shouldSave() == false || request == null) {
return this;
}
String formattedHeaderKeysString;
String formattedHeadersString;
if (request.headers != null) {
formattedHeaderKeysString = String.join(request.headers.keySet(), NEW_LINE_DELIMITER);
if (LoggerParameter.STORE_REST_REQUEST_HEADER_VALUES) {
List<String> headers = new List<String>();
for (String headerKey : request.headers.keySet()) {
headers.add(String.format(HTTP_HEADER_FORMAT, new List<String>{ headerKey, request.headers.get(headerKey) }));
}
formattedHeadersString = String.join(headers, NEW_LINE_DELIMITER);
}
}
String formattedParametersString;
if (request.params != null) {
List<String> parameters = new List<String>();
for (String headerKey : request.params.keySet()) {
parameters.add(String.format(HTTP_HEADER_FORMAT, new List<String>{ headerKey, request.params.get(headerKey) }));
}
formattedParametersString = String.join(parameters, NEW_LINE_DELIMITER);
}
TextFieldValueCleaner textCleaner = new TextFieldValueCleaner(
this.userSettings,
Schema.LogEntryEvent__e.RestRequestBody__c,
request.requestBody?.toString()
);
this.logEntryEvent.RestRequestBody__c = textCleaner.textValue;
this.logEntryEvent.RestRequestBodyMasked__c = textCleaner.wasMasked;
this.logEntryEvent.RestRequestBodyTruncated__c = textCleaner.wasTruncated;
this.logEntryEvent.RestRequestHeaderKeys__c = formattedHeaderKeysString;
this.logEntryEvent.RestRequestHeaders__c = LoggerDataStore.truncateFieldValue(Schema.LogEntryEvent__e.RestRequestHeaders__c, formattedHeadersString);
this.logEntryEvent.RestRequestMethod__c = request.httpMethod;
this.logEntryEvent.RestRequestParameters__c = formattedParametersString;
this.logEntryEvent.RestRequestRemoteAddress__c = request.remoteAddress;
this.logEntryEvent.RestRequestResourcePath__c = request.resourcePath;
this.logEntryEvent.RestRequestUri__c = request.requestURI;
return this;
}
/**
* @description Sets the log entry event's REST Response fields
* @param response The instance of `System.RestResponse` to log
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setRestResponseDetails(System.RestResponse response) {
if (this.shouldSave() == false || response == null) {
return this;
}
String formattedHeaderKeysString;
String formattedHeadersString;
if (response.headers != null) {
formattedHeaderKeysString = String.join(response.headers.keySet(), NEW_LINE_DELIMITER);
if (LoggerParameter.STORE_REST_RESPONSE_HEADER_VALUES) {
List<String> headers = new List<String>();
for (String headerKey : response.headers.keySet()) {
headers.add(String.format(HTTP_HEADER_FORMAT, new List<String>{ headerKey, response.headers.get(headerKey) }));
}
formattedHeadersString = String.join(headers, NEW_LINE_DELIMITER);
}
}
TextFieldValueCleaner textCleaner = new TextFieldValueCleaner(
this.userSettings,
Schema.LogEntryEvent__e.RestResponseBody__c,
response.responseBody?.toString()
);
this.logEntryEvent.RestResponseBody__c = textCleaner.textValue;
this.logEntryEvent.RestResponseBodyMasked__c = textCleaner.wasMasked;
this.logEntryEvent.RestResponseBodyTruncated__c = textCleaner.wasTruncated;
this.logEntryEvent.RestResponseHeaderKeys__c = formattedHeaderKeysString;
this.logEntryEvent.RestResponseHeaders__c = LoggerDataStore.truncateFieldValue(Schema.LogEntryEvent__e.RestResponseHeaders__c, formattedHeadersString);
this.logEntryEvent.RestResponseStatusCode__c = response.statusCode;
return this;
}
/**
* @description Sets a field value on the builder's `LogEntryEvent__e` record
* @param field The `Schema.SObjectField` token of the field to populate
* on the builder's `LogEntryEvent__e` record
* @param fieldValue The `Object` value to populate in the provided field
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder setField(Schema.SObjectField field, Object fieldValue) {
if (this.shouldSave() == false) {
return this;
}
return this.setField(new Map<Schema.SObjectField, Object>{ field => fieldValue });
}
/**
* @description Sets multiple field values on the builder's `LogEntryEvent__e` record
* @param fieldToValue An instance of `Map<Schema.SObjectField, Object>` containing the
* the fields & values to populate on the builder's `LogEntryEvent__e` record
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
@SuppressWarnings('PMD.AvoidDebugStatements')
global LogEntryEventBuilder setField(Map<Schema.SObjectField, Object> fieldToValue) {
if (this.shouldSave() == false || fieldToValue == null) {
return this;
}
for (Schema.SObjectField field : fieldToValue.keySet()) {
Schema.DescribeFieldResult fieldDescribe = field.getDescribe();
Object value = fieldToValue.get(field);
if (fieldDescribe.getSoapType() == Schema.SoapType.STRING) {
value = LoggerDataStore.truncateFieldValue(field, (String) value);
}
try {
this.logEntryEvent.put(field, value);
} catch (System.Exception ex) {
LogMessage logMessage = new LogMessage('Could not set field {0} with value {1}', field, value);
System.debug(System.LoggingLevel.WARN, logMessage.getMessage());
}
}
return this;
}
/**
* @description Appends the tag to the existing list of tags
* @param tag The string to use as a tag for the current entry
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder addTag(String tag) {
if (this.shouldSave() == false || String.isBlank(tag)) {
return this;
}
this.tags.add(tag);
this.tagDetailsAreSet = false;
return this;
}
/**
* @description Appends the tag to the existing list of tags
* @param tags The list of strings to use as tags for the current entry
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
global LogEntryEventBuilder addTags(List<String> tags) {
if (tags == null || tags.isEmpty()) {
return this;
}
for (String tag : tags) {
this.addTag(tag);
}
return this;
}
/**
* @description Deprecated - use `addTags(List<String> tags)` instead.
* This method will be removed in a future release
* @param tags A list of tags
* @return An instance of LogEntryEventBuilder with the given topics / tags.
*/
public LogEntryEventBuilder setTopics(List<String> tags) {
return this.addTags(tags);
}
/**
* @description Parses the provided stack trace and sets the log entry's origin & stack trace fields
* @param stackTraceString The Apex stack trace string to parse
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
@SuppressWarnings('PMD.NcssMethodCount')
global LogEntryEventBuilder parseStackTrace(String stackTraceString) {
if (this.shouldSave() == false || LoggerParameter.ENABLE_STACK_TRACE_PARSING == false) {
return this;
}
return this.parseStackTrace(new LoggerStackTrace(stackTraceString));
}
/**
* @description Determines if this instance of `LogEntryEventBuilder` should be saved the next time that `Logger.saveLog()` is called
* @return A boolean set to true if the log entries should be saved.
*/
public Boolean shouldSave() {
return this.shouldSave;
}
/**
* @description **This is only intended to be used internally by Nebula Logger, and is subject to change.**
* @param loggingContext Variables specific to the current Logger state
* Sets information only available from the `Logger` class.
*/
public void setLoggingContext(LoggingContext loggingContext) {
this.logEntryEvent.ApiVersion__c = loggingContext.organizationApiVersion;
this.logEntryEvent.EntryScenario__c = loggingContext.currentEntryScenario;
this.logEntryEvent.LoggerVersionNumber__c = loggingContext.loggerVersionNumber;
this.logEntryEvent.OrganizationApiVersion__c = loggingContext.organizationApiVersion;
this.logEntryEvent.OrganizationDomainUrl__c = loggingContext.organizationDomainUrl;
this.logEntryEvent.RequestId__c = loggingContext.requestId;
this.logEntryEvent.SystemMode__c = loggingContext.systemMode?.name();
this.logEntryEvent.TransactionEntryNumber__c = loggingContext.entryNumber;
this.logEntryEvent.TransactionId__c = loggingContext.transactionId;
this.logEntryEvent.UserLoggingLevel__c = loggingContext.userLoggingLevel.name();
this.logEntryEvent.UserLoggingLevelOrdinal__c = loggingContext.userLoggingLevel.ordinal();
}
/**
* @description **This is only intended to be used internally by Nebula Logger, and is subject to change.**
* @param timestamp Datetime instance to set timestamp fields on this.logEntryEvent
* @return The same instance of `LogEntryEventBuilder`, useful for chaining methods
*/
public LogEntryEventBuilder setTimestamp(Datetime timestamp) {
// Salesforce does not provide precise datetimes in Apex triggers for platform events
// Set the string value of timestamp to a second field as a workaround
// See https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_api_considerations.htm
this.logEntryEvent.EpochTimestamp__c = timestamp.getTime();
this.logEntryEvent.Timestamp__c = timestamp;
this.logEntryEvent.TimestampString__c = '' + this.logEntryEvent.EpochTimestamp__c;
return this;
}
/**
* @description Returns the `LogEntryEvent__e` record for this instance of LogEntryEventBuilder
* @return The `LogEntryEvent__e` record
*/
global LogEntryEvent__e getLogEntryEvent() {
if (this.shouldSave() == false) {
return null;
}
// Lazy-loading of some details to help minimize Apex heap size usage until needed
if (this.detailsAreSet == false) {
if (this.userSettings.IsAnonymousModeEnabled__c == false) {
setUserInfoDetails(this.logEntryEvent);
setQueriedAuthSessionDetails(this.logEntryEvent, this.userSettings);
setQueriedUserDetails(this.logEntryEvent, this.userSettings);
}
setQueriedNetworkDetails(this.logEntryEvent, this.userSettings);
setQueriedOrganizationDetails(this.logEntryEvent, this.userSettings);
this.detailsAreSet = true;
}
// getLogEntryEvent() and addTag() could both be called multiple times
// for the same instance of LogEntryBuilder, so tags are set (if needed)
// each time getLogEntryEvent() is called, whereas methods executed above (using Boolean
// this.detailsAreSet) only need to be run once
if (this.tagDetailsAreSet == false) {
this.setTagsDetails();
this.tagDetailsAreSet = true;
}
return this.logEntryEvent;
}
private void setSaveReason() {
System.LoggingLevel userLoggingLevel = System.LoggingLevel.valueOf(this.userSettings.LoggingLevel__c);
Boolean isEntryLoggingLevelEnabled = this.entryLoggingLevel.ordinal() >= userLoggingLevel.ordinal();
this.logEntryEvent.EntrySaveReason__c = isEntryLoggingLevelEnabled ? ENTRY_SAVE_REASON_LOGGING_LEVEL_MET : ENTRY_SAVE_REASON_OVERRIDE;
}
@SuppressWarnings('PMD.AvoidDebugStatements')
private void logToApexDebug(String message) {
if (this.userSettings.IsApexSystemDebugLoggingEnabled__c == false) {
return;
}
String template = LoggerParameter.SYSTEM_DEBUG_MESSAGE_FORMAT?.unescapeJava();
if (String.isNotBlank(template)) {
List<String> possibleReplacements = template.split('\\{');
for (String possibleReplacement : possibleReplacements) {
if (String.isBlank(possibleReplacement)) {
continue;
}
String logEntryFieldName = possibleReplacement.substringBefore('}');
Object logEntryFieldValue = this.logEntryEvent.get(logEntryFieldName);
if (logEntryFieldValue == null) {
logEntryFieldValue = '(null)';
}
template = template.replace('{' + logEntryFieldName + '}', String.valueOf(logEntryFieldValue));
}
this.debugMessage = template;
} else {
this.debugMessage = message;
}
// One of a few limited places in the codebase (except tests) that should use System.debug()
// The rest of the codebase should use a method in Logger.cls
System.debug(this.entryLoggingLevel, this.debugMessage);
}
private LogEntryEventBuilder parseStackTrace(LoggerStackTrace originStackTrace) {
if (this.shouldSave() == false || LoggerParameter.ENABLE_STACK_TRACE_PARSING == false) {
return this;
}
this.logEntryEvent.OriginLocation__c = originStackTrace.Location;
this.logEntryEvent.OriginSourceActionName__c = originStackTrace.Source?.ActionName;
this.logEntryEvent.OriginSourceApiName__c = originStackTrace.Source?.ApiName;
this.logEntryEvent.OriginSourceMetadataType__c = originStackTrace.Source?.MetadataType.name();
this.logEntryEvent.StackTrace__c = LoggerDataStore.truncateFieldValue(Schema.LogEntryEvent__e.StackTrace__c, originStackTrace.ParsedStackTraceString);
return this;
}
private LogEntryEventBuilder setDatabaseDetails(List<Object> databaseResults, System.Type resultType, Id possibleRecordId) {
if (this.shouldSave() == false) {
return this;
}
this.logEntryEvent.DatabaseResultCollectionSize__c = databaseResults.size();
this.logEntryEvent.DatabaseResultCollectionType__c = this.logEntryEvent.DatabaseResultCollectionSize__c == 1 ? 'Single' : 'List';
String serializedResult = System.JSON.serializePretty(this.logEntryEvent.DatabaseResultCollectionSize__c == 1 ? databaseResults.get(0) : databaseResults);
this.logEntryEvent.DatabaseResultJson__c = LoggerDataStore.truncateFieldValue(Schema.LogEntryEvent__e.DatabaseResultJson__c, serializedResult);
this.logEntryEvent.DatabaseResultType__c = resultType?.getName();
return this.setRecordId(possibleRecordId);
}
private void setTagsDetails() {
if (this.tags.isEmpty() || this.tagDetailsAreSet) {
return;
}
List<String> sortedTags = new List<String>(this.tags);
sortedTags.sort();
this.logEntryEvent.Tags__c = LoggerDataStore.truncateFieldValue(