From e9e2bf0e30ec560e6359e844b3e2f75eca861ad1 Mon Sep 17 00:00:00 2001 From: Anand Chapla Date: Tue, 28 Mar 2023 14:05:37 +0530 Subject: [PATCH] Cache UserName and Domain to improve performance when creating new EcsDocument (#287) Co-authored-by: Lightning Unicorn Co-authored-by: Martijn Laarman --- src/Elastic.CommonSchema/EcsDocument.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Elastic.CommonSchema/EcsDocument.cs b/src/Elastic.CommonSchema/EcsDocument.cs index 5c690e7d..0307cbc0 100644 --- a/src/Elastic.CommonSchema/EcsDocument.cs +++ b/src/Elastic.CommonSchema/EcsDocument.cs @@ -57,9 +57,7 @@ public static TEcsDocument CreateNewWithDefaults( if (options?.IncludeHost is null or true) doc.Host = GetHost(); if (options?.IncludeProcess is null or true) doc.Process = GetProcess(); - // TODO I think we can cache user? does CurrentPrincipal on Thread ever change? - if (options?.IncludeUser is null or true) - doc.User = new User { Id = Thread.CurrentPrincipal?.Identity.Name, Name = Environment.UserName, Domain = Environment.UserDomainName }; + if (options?.IncludeUser is null or true) doc.User = GetUser(); return doc; } @@ -157,6 +155,12 @@ private static Process GetProcess() }; } + private static readonly string UserName = Environment.UserName; + private static readonly string UserDomainName = Environment.UserDomainName; + + //Can not cache current thread's identity as it's used for role based security, different threads can have different identities + private static User GetUser() => new User { Id = Thread.CurrentPrincipal?.Identity.Name, Name = UserName, Domain = UserDomainName }; + private static Error GetError(Exception exception) { if (exception == null)