-
Notifications
You must be signed in to change notification settings - Fork 55
/
Logger.cpp
969 lines (831 loc) · 32.4 KB
/
Logger.cpp
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
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
#include "Logger.hpp"
#include "CommonFields.h"
#include "LogSessionData.hpp"
#include "NullObjects.hpp"
#include "utils/Utils.hpp"
#include <algorithm>
#include <array>
using namespace MAT;
namespace MAT_NS_BEGIN
{
class ActiveLoggerCall
{
public:
const Logger& m_logger;
bool m_active;
bool m_unpaused;
ActiveLoggerCall(ActiveLoggerCall const& source) : m_logger(source.m_logger)
{
m_unpaused = m_logger.m_logManager.StartActivity();
std::lock_guard<std::mutex> lock(m_logger.m_shutdown_mutex);
m_active = m_logger.m_active;
if (m_active)
{
m_logger.m_active_count += 1;
}
}
/// Record current state on construction; increment active
/// count if we are active.
explicit ActiveLoggerCall(const Logger& parent) :
m_logger(parent)
{
m_unpaused = m_logger.m_logManager.StartActivity();
std::lock_guard<std::mutex> lock(m_logger.m_shutdown_mutex);
m_active = m_logger.m_active;
if (m_active)
{
m_logger.m_active_count += 1;
}
}
/// If active, decrement active count, wake any listeners when
/// active count reaches zero (usually there are no listeners).
~ActiveLoggerCall()
{
if (m_unpaused)
{
m_logger.m_logManager.EndActivity();
}
if (m_active)
{
std::lock_guard<std::mutex> lock(m_logger.m_shutdown_mutex);
if (m_logger.m_active_count > 0)
{
m_logger.m_active_count -= 1;
if (m_logger.m_active_count == 0)
{
const_cast<std::condition_variable*>(&m_logger.m_shutdown_condition)->notify_all();
}
}
}
}
bool LoggerIsDead() const noexcept
{
return !m_active || !m_unpaused;
}
};
static NullLogManager nullManager;
Logger::Logger(
const std::string& tenantToken,
const std::string& source,
const std::string& scope,
ILogManagerInternal& logManager,
ContextFieldsProvider& parentContext,
IRuntimeConfig& runtimeConfig) :
m_tenantToken(tenantToken),
m_source(source),
// TODO: scope parameter can be used to rewire the logger to alternate context.
// Scope must uniquely identify the "shared context" instance id.
m_scope(scope),
m_level(DIAG_LEVEL_DEFAULT),
m_logManager(logManager),
m_context(&parentContext),
m_config(runtimeConfig),
m_baseDecorator(logManager),
m_eventPropertiesDecorator(logManager),
m_semanticContextDecorator(logManager, m_context),
m_semanticApiDecorators(logManager),
m_sessionStartTime(0),
m_allowDotsInType(false),
m_resetSessionOnEnd(false)
{
std::string tenantId = tenantTokenToId(m_tenantToken);
LOG_TRACE("%p: New instance (tenantId=%s)", this, tenantId.c_str());
m_iKey = "o:" + tenantId;
if (m_config.HasConfig(CFG_MAP_COMPAT))
{
MAT::VariantMap& cfg = m_config[CFG_MAP_COMPAT];
m_allowDotsInType = cfg[CFG_BOOL_COMPAT_DOTS];
m_customTypePrefix = static_cast<std::string&>(cfg[CFG_STR_COMPAT_PREFIX]);
}
m_resetSessionOnEnd = m_config[CFG_BOOL_SESSION_RESET_ENABLED];
// Special scope "-" - means opt-out from parent context variables auto-capture.
// It allows to detach the logger from its parent context.
// This is the default mode for C API guests.
if (m_scope == CONTEXT_SCOPE_NONE)
{
SetParentContext(nullptr);
}
}
Logger::~Logger() noexcept
{
LOG_TRACE("%p: Destroyed", this);
}
ISemanticContext* Logger::GetSemanticContext() const
{
return (ISemanticContext*)(&m_context);
}
/******************************************************************************
* Logger::SetContext
*
* Set app/session context fields.
*
* Could be used to overwrite the auto-populated(Part A) context fields
* (ie. m_commonContextFields)
*
******************************************************************************/
void Logger::SetContext(const std::string& name, const EventProperty& prop)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return;
}
LOG_TRACE("%p: SetContext( properties.name=\"%s\", properties.value=\"%s\", PII=%u, ...)",
this, name.c_str(), prop.to_string().c_str(), prop.piiKind);
const EventRejectedReason isValidPropertyName = validatePropertyName(name);
if (isValidPropertyName != REJECTED_REASON_OK)
{
LOG_ERROR("Context name is invalid: %s", name.c_str());
DebugEvent evt;
evt.type = DebugEventType::EVT_REJECTED;
evt.param1 = isValidPropertyName;
DispatchEvent(evt);
return;
}
// Always overwrite the stored value.
// Empty string is allowed to remove the previously set value.
// If the value is empty, the context will not be added to event.
m_context.SetCustomField(name, prop);
}
void Logger::SetContext(const std::string& k, const char v[], PiiKind pii)
{
SetContext(k, EventProperty(v, pii));
};
void Logger::SetContext(const std::string& k, const std::string& v, PiiKind pii)
{
SetContext(k, EventProperty(v, pii));
};
void Logger::SetContext(const std::string& k, double v, PiiKind pii)
{
SetContext(k, EventProperty(v, pii));
};
void Logger::SetContext(const std::string& k, int64_t v, PiiKind pii)
{
SetContext(k, EventProperty(v, pii));
};
void Logger::SetContext(const std::string& k, time_ticks_t v, PiiKind pii)
{
SetContext(k, EventProperty(v, pii));
};
void Logger::SetContext(const std::string& k, GUID_t v, PiiKind pii)
{
SetContext(k, EventProperty(v, pii));
};
void Logger::SetContext(const std::string& k, bool v, PiiKind pii)
{
SetContext(k, EventProperty(v, pii));
};
// The goal of this method is to rewire the logger instance to any other ISemanticContext issued by SDK.
// SDK may provide a future option for a guest logger to opt-in into its own semantic context. The method will then
// rewire from the default parent (Host LogManager context) to guest's sandbox context, i.e. enabling scenario where
// several guests are attached to one host, but each guest has their own 'local' LogManager semantic context sandbox.
// ...
// LogManager<T>::SetContext(...); // issued by guests would also allow to set context variable on guest's sandbox.
//
// C API does not expose shared context to the callers. Default option for C API 'guest' customers is to detach them
// from the parent logger via ILogger::SetParentContext(nullptr)
//
void Logger::SetParentContext(ISemanticContext* context)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return;
}
if (context == nullptr)
{
// Since common props would typically be populated by the root-level
// LogManager instance and we are detaching from that one, we need
// to populate this context with common props directly.
PAL::registerSemanticContext(&m_context);
}
m_context.SetParentContext(static_cast<ContextFieldsProvider*>(context));
}
/// <summary>
/// Logs the application lifecycle.
/// </summary>
/// <param name="state">The state.</param>
/// <param name="properties">The properties.</param>
void Logger::LogAppLifecycle(AppLifecycleState state, EventProperties const& properties)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return;
}
LOG_TRACE("%p: LogAppLifecycle(state=%u, properties.name=\"%s\", ...)",
this, state, properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
if (!CanEventPropertiesBeSent(properties))
{
DispatchEvent(DebugEventType::EVT_FILTERED);
return;
}
EventLatency latency = EventLatency_Normal;
::CsProtocol::Record record;
const bool decorated =
applyCommonDecorators(record, properties, latency) &&
m_semanticApiDecorators.decorateAppLifecycleMessage(record, state);
if (!decorated)
{
LOG_ERROR("Failed to log %s event %s/%s: invalid arguments provided",
"AppLifecycle", tenantTokenToId(m_tenantToken).c_str(), properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
return;
}
submit(record, properties);
DispatchEvent(DebugEvent(DebugEventType::EVT_LOG_LIFECYCLE, size_t(latency), size_t(0), static_cast<void*>(&record), sizeof(record)));
}
/// <summary>
/// Logs the custom event with the specified name.
/// </summary>
/// <param name="name">A string that contains the name of the custom event.</param>
void Logger::LogEvent(std::string const& name)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return;
}
EventProperties event(name);
LogEvent(event);
}
/// <summary>
/// Logs the event.
/// </summary>
/// <param name="properties">The properties.</param>
void Logger::LogEvent(EventProperties const& properties)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return;
}
// SendAsJSON(properties, m_tenantToken);
LOG_TRACE("%p: LogEvent(properties.name=\"%s\", ...)",
this, properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
if (!CanEventPropertiesBeSent(properties))
{
DispatchEvent(DebugEventType::EVT_FILTERED);
return;
}
EventLatency latency = EventLatency_Normal;
if (properties.GetLatency() > EventLatency_Unspecified)
{
latency = properties.GetLatency();
}
::CsProtocol::Record record;
if (!applyCommonDecorators(record, properties, latency))
{
LOG_ERROR("Failed to log %s event %s/%s: invalid arguments provided",
"custom",
tenantTokenToId(m_tenantToken).c_str(),
properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
return;
}
submit(record, properties);
DispatchEvent(DebugEvent(DebugEventType::EVT_LOG_EVENT, size_t(latency), size_t(0), static_cast<void*>(&record), sizeof(record)));
}
/// <summary>
/// Logs a failure event - such as an application exception.
/// </summary>
/// <param name="signature">A string that contains the signature that identifies the bucket of the failure.</param>
/// <param name="detail">A string that contains a description of the failure.</param>
/// <param name="category">A string that contains the category of the failure - such as an application error,
/// application not responding, or application crash</param>
/// <param name="id">A string that contains the identifier that uniquely identifies this failure.</param>
/// <param name="properties">Properties of this failure event, specified using an EventProperties object.</param>
void Logger::LogFailure(
std::string const& signature,
std::string const& detail,
std::string const& category,
std::string const& id,
EventProperties const& properties)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return;
}
LOG_TRACE("%p: LogFailure(signature=\"%s\", properties.name=\"%s\", ...)",
this, signature.c_str(), properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
if (!CanEventPropertiesBeSent(properties))
{
DispatchEvent(DebugEventType::EVT_FILTERED);
return;
}
EventLatency latency = EventLatency_Normal;
::CsProtocol::Record record;
const bool decorated =
applyCommonDecorators(record, properties, latency) &&
m_semanticApiDecorators.decorateFailureMessage(record, signature, detail, category, id);
if (!decorated)
{
LOG_ERROR("Failed to log %s event %s/%s: invalid arguments provided",
"Failure",
tenantTokenToId(m_tenantToken).c_str(), properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
return;
}
submit(record, properties);
DispatchEvent(DebugEvent(DebugEventType::EVT_LOG_FAILURE, size_t(latency), size_t(0), static_cast<void*>(&record), sizeof(record)));
}
void Logger::LogFailure(
std::string const& signature,
std::string const& detail,
EventProperties const& properties)
{
// this inner call to LogFailure will instantiate ActiveCall
LogFailure(signature, detail, "", "", properties);
}
void Logger::LogPageView(
std::string const& id,
std::string const& pageName,
std::string const& category,
std::string const& uri,
std::string const& referrer,
EventProperties const& properties)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return;
}
LOG_TRACE("%p: LogPageView(id=\"%s\", properties.name=\"%s\", ...)",
this, id.c_str(), properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
if (!CanEventPropertiesBeSent(properties))
{
DispatchEvent(DebugEventType::EVT_FILTERED);
return;
}
EventLatency latency = EventLatency_Normal;
::CsProtocol::Record record;
const bool decorated =
applyCommonDecorators(record, properties, latency) &&
m_semanticApiDecorators.decoratePageViewMessage(record, id, pageName, category, uri, referrer);
if (!decorated)
{
LOG_ERROR("Failed to log %s event %s/%s: invalid arguments provided",
"PageView", tenantTokenToId(m_tenantToken).c_str(), properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
return;
}
submit(record, properties);
DispatchEvent(DebugEvent(DebugEventType::EVT_LOG_PAGEVIEW, size_t(latency), size_t(0), (void*)(&record), sizeof(record)));
}
void Logger::LogPageView(
std::string const& id,
std::string const& pageName,
EventProperties const& properties)
{
LogPageView(id, pageName, "", "", "", properties);
}
void Logger::LogPageAction(
std::string const& pageViewId,
ActionType actionType,
EventProperties const& properties)
{
PageActionData pageActionData(pageViewId, actionType);
LogPageAction(pageActionData, properties);
}
void Logger::LogPageAction(
PageActionData const& pageActionData,
EventProperties const& properties)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return;
}
LOG_TRACE("%p: LogPageAction(pageActionData.actionType=%u, properties.name=\"%s\", ...)",
this, pageActionData.actionType, properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
if (!CanEventPropertiesBeSent(properties))
{
DispatchEvent(DebugEventType::EVT_FILTERED);
return;
}
EventLatency latency = EventLatency_Normal;
::CsProtocol::Record record;
const bool decorated =
applyCommonDecorators(record, properties, latency) &&
m_semanticApiDecorators.decoratePageActionMessage(record, pageActionData);
if (!decorated)
{
LOG_ERROR("Failed to log %s event %s/%s: invalid arguments provided",
"PageAction", tenantTokenToId(m_tenantToken).c_str(), properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
return;
}
submit(record, properties);
DispatchEvent(DebugEvent(DebugEventType::EVT_LOG_PAGEACTION, size_t(latency), size_t(0), (void*)(&record), sizeof(record)));
}
/// <summary>
/// Applies the common decorators.
/// </summary>
/// <param name="record">The record.</param>
/// <param name="properties">The properties.</param>
/// <param name="latency">The latency.</param>
/// <returns></returns>
bool Logger::applyCommonDecorators(::CsProtocol::Record& record, EventProperties const& properties, EventLatency& latency)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return false;
}
record.name = properties.GetName();
record.baseType = m_customTypePrefix;
std::string evtType = properties.GetType();
if (!evtType.empty())
{
if (!record.baseType.empty())
{
record.baseType.append(".");
}
if (!m_allowDotsInType)
{
std::replace(evtType.begin(), evtType.end(), '.', '_');
}
record.baseType.append(evtType);
}
if (record.name.empty())
{
record.name = "NotSpecified";
}
record.iKey = m_iKey;
return m_baseDecorator.decorate(record) && m_semanticContextDecorator.decorate(record) && m_eventPropertiesDecorator.decorate(record, latency, properties);
}
void Logger::submit(::CsProtocol::Record& record, const EventProperties& props)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return;
}
const auto policyBitFlags = props.GetPolicyBitFlags();
const auto persistence = props.GetPersistence();
const auto latency = props.GetLatency();
auto levelFilter = m_logManager.GetLevelFilter();
if (levelFilter.IsLevelFilterEnabled())
{
const auto& m_props = props.GetProperties();
const auto it = m_props.find(COMMONFIELDS_EVENT_LEVEL);
//
// Level policy:
// * get level from the COMMONFIELDS_EVENT_LEVEL property if set
// * if not set, then get level from the ILogger instance
// * if not set, then get level from the LogManager instance
// * if still not set (no default assigned at LogManager scope),
// then prefer to drop. This is user error: user set the range
// restrition, but didn't specify the defaults.
//
uint8_t level = (it != m_props.cend()) ? static_cast<uint8_t>(it->second.as_int64) : m_level;
if (level == DIAG_LEVEL_DEFAULT)
{
level = levelFilter.GetDefaultLevel();
if (level == DIAG_LEVEL_DEFAULT)
{
// If no default level, but restrictions are in effect, then prefer to drop event
LOG_INFO("Event %s/%s dropped: no diagnostic level assigned!",
tenantTokenToId(m_tenantToken).c_str(), record.baseType.c_str());
DispatchEvent(DebugEventType::EVT_FILTERED);
return;
}
}
if (!levelFilter.IsLevelEnabled(level))
{
DispatchEvent(DebugEventType::EVT_FILTERED);
return;
}
}
if (latency == EventLatency_Off)
{
DispatchEvent(DebugEventType::EVT_DROPPED);
LOG_INFO("Event %s/%s dropped: calculated latency 0 (Off)",
tenantTokenToId(m_tenantToken).c_str(), record.baseType.c_str());
return;
}
// TODO: [MG] - check if optimization is possible in generateUuidString
IncomingEventContext event(PAL::generateUuidString(), m_tenantToken, latency, persistence, &record);
event.policyBitFlags = policyBitFlags;
m_logManager.sendEvent(&event);
}
void Logger::onSubmitted()
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return;
}
LOG_INFO("This method is executed from worker thread");
}
void Logger::LogSampledMetric(
std::string const& name,
double value,
std::string const& units,
std::string const& instanceName,
std::string const& objectClass,
std::string const& objectId,
EventProperties const& properties)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return;
}
LOG_TRACE("%p: LogSampledMetric(name=\"%s\", properties.name=\"%s\", ...)",
this, name.c_str(), properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
if (!CanEventPropertiesBeSent(properties))
{
DispatchEvent(DebugEventType::EVT_FILTERED);
return;
}
EventLatency latency = EventLatency_Normal;
::CsProtocol::Record record;
const bool decorated =
applyCommonDecorators(record, properties, latency) &&
m_semanticApiDecorators.decorateSampledMetricMessage(record, name, value, units, instanceName, objectClass, objectId);
if (!decorated)
{
LOG_ERROR("Failed to log %s event %s/%s: invalid arguments provided",
"SampledMetric", tenantTokenToId(m_tenantToken).c_str(), properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
return;
}
submit(record, properties);
DispatchEvent(DebugEvent(DebugEventType::EVT_LOG_SAMPLEMETR, size_t(latency), size_t(0), (void*)(&record), sizeof(record)));
}
void Logger::LogSampledMetric(
std::string const& name,
double value,
std::string const& units,
EventProperties const& properties)
{
LogSampledMetric(name, value, units, "", "", "", properties);
}
void Logger::LogAggregatedMetric(
std::string const& name,
long duration,
long count,
EventProperties const& properties)
{
AggregatedMetricData metricData(name, duration, count);
LogAggregatedMetric(metricData, properties);
}
void Logger::LogAggregatedMetric(
AggregatedMetricData const& metricData,
EventProperties const& properties)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return;
}
LOG_TRACE("%p: LogAggregatedMetric(name=\"%s\", properties.name=\"%s\", ...)",
this, metricData.name.c_str(), properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
if (!CanEventPropertiesBeSent(properties))
{
DispatchEvent(DebugEventType::EVT_FILTERED);
return;
}
EventLatency latency = EventLatency_Normal;
::CsProtocol::Record record;
const bool decorated =
applyCommonDecorators(record, properties, latency) &&
m_semanticApiDecorators.decorateAggregatedMetricMessage(record, metricData);
if (!decorated)
{
LOG_ERROR("Failed to log %s event %s/%s: invalid arguments provided",
"AggregatedMetric", tenantTokenToId(m_tenantToken).c_str(), properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
return;
}
submit(record, properties);
DispatchEvent(DebugEvent(DebugEventType::EVT_LOG_AGGRMETR, size_t(latency), size_t(0), (void*)(&record), sizeof(record)));
}
void Logger::LogTrace(
TraceLevel level,
std::string const& message,
EventProperties const& properties)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return;
}
LOG_TRACE("%p: LogTrace(level=%u, properties.name=\"%s\", ...)",
this, level, properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
if (!CanEventPropertiesBeSent(properties))
{
DispatchEvent(DebugEventType::EVT_FILTERED);
return;
}
EventLatency latency = EventLatency_Normal;
::CsProtocol::Record record;
bool decorated =
applyCommonDecorators(record, properties, latency) &&
m_semanticApiDecorators.decorateTraceMessage(record, level, message);
if (!decorated)
{
LOG_ERROR("Failed to log %s event %s/%s: invalid arguments provided",
"Trace", tenantTokenToId(m_tenantToken).c_str(), properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
return;
}
submit(record, properties);
DispatchEvent(DebugEvent(DebugEventType::EVT_LOG_TRACE, size_t(latency), size_t(0), (void*)(&record), sizeof(record)));
}
void Logger::LogUserState(
UserState state,
long timeToLiveInMillis,
EventProperties const& properties)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return;
}
LOG_TRACE("%p: LogUserState(state=%u, properties.name=\"%s\", ...)",
this, state, properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
if (!CanEventPropertiesBeSent(properties))
{
DispatchEvent(DebugEventType::EVT_FILTERED);
return;
}
EventLatency latency = EventLatency_Normal;
::CsProtocol::Record record;
bool decorated =
applyCommonDecorators(record, properties, latency) &&
m_semanticApiDecorators.decorateUserStateMessage(record, state, timeToLiveInMillis);
if (!decorated)
{
LOG_ERROR("Failed to log %s event %s/%s: invalid arguments provided",
"UserState", tenantTokenToId(m_tenantToken).c_str(), properties.GetName().empty() ? "<unnamed>" : properties.GetName().c_str());
return;
}
submit(record, properties);
DispatchEvent(DebugEvent(DebugEventType::EVT_LOG_USERSTATE, size_t(latency), size_t(0), (void*)(&record), sizeof(record)));
}
/******************************************************************************
* Logger::LogSession
*
* Log a user's Session.
*
******************************************************************************/
void Logger::LogSession(SessionState state, const EventProperties& props)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return;
}
if (!CanEventPropertiesBeSent(props))
{
DispatchEvent(DebugEventType::EVT_FILTERED);
return;
}
auto logSessionData = m_logManager.GetLogSessionData();
std::string sessionSDKUid;
unsigned long long sessionFirstTime = 0;
if (logSessionData!=nullptr)
{
sessionSDKUid = logSessionData->getSessionSDKUid();
sessionFirstTime = logSessionData->getSessionFirstTime();
}
if (sessionSDKUid == "" || sessionFirstTime == 0)
{
LOG_WARN("We don't have a first time so no session logged");
return;
}
EventRejectedReason isValidEventName = validateEventName(props.GetName());
if (isValidEventName != REJECTED_REASON_OK)
{
LOG_ERROR("Invalid event properties!");
DebugEvent evt;
evt.type = DebugEventType::EVT_REJECTED;
evt.param1 = isValidEventName;
DispatchEvent(evt);
return;
}
int64_t sessionDuration = 0;
switch (state)
{
case SessionState::Session_Started:
{
if (m_sessionStartTime > 0)
{
LOG_ERROR("LogSession The order is not the correct one in calling LogSession");
return;
}
m_sessionStartTime = PAL::getUtcSystemTime();
m_sessionId = PAL::generateUuidString();
break;
}
case SessionState::Session_Ended:
{
if (m_sessionStartTime == 0)
{
LOG_WARN("LogSession We don't have session start time");
return;
}
sessionDuration = PAL::getUtcSystemTime() - m_sessionStartTime;
if (m_resetSessionOnEnd)
{
// reset the time of the session to 0 and get a new sessionId
m_sessionStartTime = 0;
if (logSessionData!=nullptr)
{
m_logManager.ResetLogSessionData();
LOG_TRACE("Resetting session data on session end");
}
}
break;
}
}
EventLatency latency = EventLatency_RealTime;
::CsProtocol::Record record;
bool decorated = applyCommonDecorators(record, props, latency) &&
m_semanticApiDecorators.decorateSessionMessage(record, state, m_sessionId, PAL::formatUtcTimestampMsAsISO8601(sessionFirstTime), sessionSDKUid, sessionDuration);
if (!decorated)
{
LOG_ERROR("Failed to log %s event %s/%s: invalid arguments provided",
"Trace", tenantTokenToId(m_tenantToken).c_str(), props.GetName().empty() ? "<unnamed>" : props.GetName().c_str());
return;
}
submit(record, props);
DispatchEvent(DebugEvent(DebugEventType::EVT_LOG_SESSION, size_t(latency), size_t(0), (void*)(&record), sizeof(record)));
}
IEventFilterCollection& Logger::GetEventFilters() noexcept
{
return m_filters;
}
const IEventFilterCollection& Logger::GetEventFilters() const noexcept
{
return m_filters;
}
ILogManager& Logger::GetParent()
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return nullManager;
}
return m_logManager;
}
LogSessionData* Logger::GetLogSessionData()
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return nullManager.GetLogSessionData();
}
return m_logManager.GetLogSessionData();
}
IAuthTokensController* Logger::GetAuthTokensController()
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return nullManager.GetAuthTokensController();
}
return m_logManager.GetAuthTokensController();
}
bool Logger::DispatchEvent(DebugEvent evt)
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return nullManager.DispatchEvent(std::move(evt));
}
return m_logManager.DispatchEvent(std::move(evt));
}
std::string Logger::GetSource()
{
return m_source;
}
void Logger::SetLevel(uint8_t level)
{
m_level = level;
}
bool Logger::CanEventPropertiesBeSent(EventProperties const& properties) const noexcept
{
ActiveLoggerCall active(*this);
if (active.LoggerIsDead())
{
return false;
}
return m_filters.CanEventPropertiesBeSent(properties) && m_logManager.GetEventFilters().CanEventPropertiesBeSent(properties);
}
void Logger::RecordShutdown()
{
std::unique_lock<std::mutex> shutdownLock(m_shutdown_mutex);
m_active = false;
if (m_active_count > 0)
{
// wait for idle before continuing
// as with all condition variables, we hold the lock,
// so no thread can decrement m_active_count until
// wait() releases (and later reacquires) the lock.
m_shutdown_condition.wait(shutdownLock, [this]() {
return m_active_count == 0; // we hold the lock for this call
});
}
}
}
MAT_NS_END