From b29bc98ee48deb3a7c49105e8008bf31603ca675 Mon Sep 17 00:00:00 2001 From: Marco Date: Tue, 5 Oct 2021 16:21:01 +0200 Subject: [PATCH] Add DeviceId enricher based on SecureStorage --- .../Enrichers/DeviceInfo/DeviceIdEnricher.cs | 28 +++++++++++++++++++ .../EnrichersConfigurationExtensions.cs | 15 +++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 nightly.serilog.xamarin/nightly.serilog.xamarin/Enrichers/DeviceInfo/DeviceIdEnricher.cs diff --git a/nightly.serilog.xamarin/nightly.serilog.xamarin/Enrichers/DeviceInfo/DeviceIdEnricher.cs b/nightly.serilog.xamarin/nightly.serilog.xamarin/Enrichers/DeviceInfo/DeviceIdEnricher.cs new file mode 100644 index 0000000..833b166 --- /dev/null +++ b/nightly.serilog.xamarin/nightly.serilog.xamarin/Enrichers/DeviceInfo/DeviceIdEnricher.cs @@ -0,0 +1,28 @@ +using System; +using Serilog.Core; +using Serilog.Events; +using Xamarin.Essentials; + +namespace nightly.serilog.xamarin.Enrichers.DeviceInfo +{ + public class DeviceIdEnricher : ILogEventEnricher + { + private LogEventProperty _cachedProperty; + + public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) + { + if (this._cachedProperty == null) + { + var idValue = SecureStorage.GetAsync("ENRICHER_ID").Result; + if (idValue == null) + { + idValue = Guid.NewGuid().ToString("N"); + SecureStorage.SetAsync("ENRICHER_ID", idValue).Wait(); + } + + this._cachedProperty = propertyFactory.CreateProperty("DeviceId", idValue); + } + logEvent.AddPropertyIfAbsent(this._cachedProperty); + } + } +} \ No newline at end of file diff --git a/nightly.serilog.xamarin/nightly.serilog.xamarin/EnrichersConfigurationExtensions.cs b/nightly.serilog.xamarin/nightly.serilog.xamarin/EnrichersConfigurationExtensions.cs index 5e019e4..edf35f0 100644 --- a/nightly.serilog.xamarin/nightly.serilog.xamarin/EnrichersConfigurationExtensions.cs +++ b/nightly.serilog.xamarin/nightly.serilog.xamarin/EnrichersConfigurationExtensions.cs @@ -5,12 +5,25 @@ using nightly.serilog.xamarin.Enrichers.Version; using Serilog; using Serilog.Configuration; -using Xamarin.Essentials; namespace nightly.serilog.xamarin { public static class EnrichersConfigurationExtensions { + + /// + /// Add univoque id to device + /// Value is stored in SecureStorage + /// + /// + /// + /// + public static LoggerConfiguration WithDeviceId(this LoggerEnrichmentConfiguration enrichment) + { + if (enrichment == null) throw new ArgumentNullException(nameof(enrichment)); + return enrichment.With(); + } + /// /// Add Session Id ///