public static object GetFirstValue(this FormattedLogValues lv)
        {
            var field  = lv.GetType().GetField("_values", BindingFlags.NonPublic | BindingFlags.Instance);
            var values = (object[])field.GetValue(lv);

            return(values?.FirstOrDefault());
        }
        public static string GetOriginalValue(this FormattedLogValues lv)
        {
            var field           = lv.GetType().GetField("_originalMessage", BindingFlags.NonPublic | BindingFlags.Instance);
            var originalMessage = (string)field.GetValue(lv);

            return((string)lv.LastOrDefault().Value ?? originalMessage);
        }
Beispiel #3
0
        public static Dictionary <string, object> GetLogMessageState(bool triggerAlert, string message, params object[] args)
        {
            Dictionary <string, object> messageState = new Dictionary <string, object>();

            var aspnetcoreEnvironment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            if (aspnetcoreEnvironment == EnvironmentName.Production || aspnetcoreEnvironment == EnvironmentName.Staging || aspnetcoreEnvironment == EnvironmentName.Development)
            {
                for (var index = 0; index < args.Length; index++)
                {
                    object arg = args[index];
                    if (arg is string)
                    {
                        args[index] = SanitizeLogOutput.RedactSensitiveInfo(arg.ToString());
                    }
                }
            }

            string formattedLogValues = new FormattedLogValues(message, args).ToString();

            messageState.Add("Message", formattedLogValues);
            messageState.Add("TriggerAlert", triggerAlert ? bool.TrueString.ToLower() : bool.FalseString.ToLower());

            return(messageState);
        }
        public void SetSimpleValueSuccessfully()
        {
            var original = new FormattedLogValues("The first number is {first} and the second is {second}", 10.ToString(), 20.ToString());
            var updated  = original.SetSimpleValue("Changed");

            Assert.Equal("Changed", updated.ToString());
        }
        /// <summary>
        /// This method is called whenever claims about the user are requested (e.g. during token creation or via the userinfo endpoint)
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public virtual Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var logValues = new FormattedLogValues("Get profile called for subject {subject} from client {client} with claim types {claimTypes} via {caller}",
                                                   context.Subject.GetSubjectId(),
                                                   context.Client.ClientName ?? context.Client.ClientId,
                                                   context.RequestedClaimTypes,
                                                   context.Caller);

            Logger.LogDebug(logValues.ToString());

            if (context.RequestedClaimTypes.Any())
            {
                var user = Users.FindBySubjectId(context.Subject.GetSubjectId());
                if (user != null)
                {
                    context.AddFilteredClaims(user.Claims);
                }
                else
                {
                    Logger.LogWarning("Users.FindBySubjectId returned null when " + logValues.ToString());
                }
            }

            return(Task.FromResult(0));
        }
        public void UpdatesValuesSuccessfully()
        {
            var original = new FormattedLogValues("The first number is {first} and the second is {second}", 10.ToString(), 20.ToString());
            var updated  = original.SetValues(20.ToString(), 30.ToString());

            Assert.Equal("The first number is 20 and the second is 30", updated.ToString());
        }
        public void GetsOriginalValueSuccessfully()
        {
            var original      = new FormattedLogValues("The first number is {first} and the second is {second}", 10.ToString(), 20.ToString());
            var originalValue = original.GetOriginalValue();

            Assert.Equal("The first number is {first} and the second is {second}", originalValue);
        }
        public void ClonesSimpleSuccessfully()
        {
            var original = new FormattedLogValues("Foo");
            var cloned   = original.Clone();

            Assert.Equal(original.ToString(), cloned.ToString());
        }
Beispiel #9
0
        public void Log(Severity severity, LoggerType loggerType, string caller, string message, IPEndPoint myIPEndPoint, Exception exception, int eventCode = 0)
        {
            var logger             = _loggerFactory.CreateLogger(caller);
            var formattedLogValues = new FormattedLogValues("{LoggerType} - {IPEndpoint}: {Message}", loggerType, myIPEndPoint, message);

            logger.Log(Map(severity), eventCode, formattedLogValues, exception, (state, ex) => state.ToString());
        }
 public void LogValues_With_UnbalancedBraces(string format)
 {
     Assert.Throws <FormatException>(() =>
     {
         var logValues = new FormattedLogValues(format);
         logValues.Format();
     });
 }
        public void ClonesComplexSuccessfully()
        {
            var original = new FormattedLogValues("The first number is {first} and the second is {second}", 10.ToString(), 20.ToString());
            var cloned   = original.Clone();

            Assert.Equal(original.ToString(), cloned.ToString());
            Assert.True(original.GetValues().SequenceEqual(cloned.GetValues()));
        }
 public void LogValues_With_UnbalancedBraces(string format)
 {
     Assert.Throws <FormatException>(() =>
     {
         var logValues = new FormattedLogValues(format, new object[] { "arg1" });
         logValues.ToString();
     });
 }
        public void LogValues_With_Basic_Types(string expected, string format, object[] args)
        {
            var logValues = new FormattedLogValues(format, args);

            Assert.Equal(expected, logValues.ToString());

            // Original format is expected to be returned from GetValues.
            Assert.Equal(format, logValues.First(v => v.Key == "{OriginalFormat}").Value);
        }
        public void LogValues_With_DateTime(string expected, string format)
        {
            var dateTime  = new DateTime(2015, 1, 1, 1, 1, 1);
            var logValues = new FormattedLogValues(format, new object[] { dateTime, dateTime });

            Assert.Equal(expected, logValues.ToString());

            // Original format is expected to be returned from GetValues.
            Assert.Equal(format, logValues.First(v => v.Key == "{OriginalFormat}").Value);
        }
        public static void LogStash(this ILogger logger, LogLevel level, EventId id, HttpContext context,
                                    Exception exception, string message, params object[] args)
        {
            if (message != null)
            {
                message = new FormattedLogValues(message, args).ToString();
            }
            var logEntry = CreateLogEntry(context, id, exception, message, level);

            logger.Log <RedisLogEntry>(level, id, logEntry, exception, DefaultMessageFormatter);
        }
        public static FormattedLogValues Clone(this FormattedLogValues original)
        {
            var field  = original.GetType().GetField("_values", BindingFlags.NonPublic | BindingFlags.Instance);
            var values = (object[])field.GetValue(original);

            field = original.GetType().GetField("_originalMessage", BindingFlags.NonPublic | BindingFlags.Instance);
            var originalMessage = (string)field.GetValue(original);

            field = original.GetType().GetField("_formatter", BindingFlags.NonPublic | BindingFlags.Instance);
            var formatter = (LogValuesFormatter)field.GetValue(original);

            return(new FormattedLogValues(formatter?.OriginalFormat ?? originalMessage, values));
        }
        public void CachedFormattersAreCapped()
        {
            for (var i = 0; i < FormattedLogValues.MaxCachedFormatters; ++i)
            {
                var ignore = new FormattedLogValues($"{i}{{i}}", i);
            }

            // check cached formatter
            var formatter = new FormattedLogValues("0{i}", 0).Formatter;

            Assert.Same(formatter, new FormattedLogValues("0{i}", 0).Formatter);

            // check non-cached formatter
            formatter = new FormattedLogValues("test {}", 0).Formatter;
            Assert.NotSame(formatter, new FormattedLogValues("test {}", 0).Formatter);
        }
        public FormattedLogValuesCollection(string format, object[] formatValues, IReadOnlyDictionary <string, object> additionalValues)
        {
            if (formatValues != null)
            {
                _formatter = new FormattedLogValues(format, formatValues);
            }
            else
            {
                _formatter = new FormattedLogValues(format);
            }

            _additionalValues = additionalValues?.ToList();

            if (_additionalValues == null)
            {
                _additionalValues = new List <KeyValuePair <string, object> >();
            }
        }
Beispiel #19
0
        public void TestLoggerLogsAllTheIndividualParamsForStructuredDataUsingFormattedLogValuesWithDuplicateParameterNames()
        {
            LogEntry loggedEntry = null;

            A.CallTo(() => fakeEventHubLog.Log(A <LogEntry> .Ignored)).Invokes((LogEntry l) => loggedEntry = l);

            var eventHubLogger = CreateTestEventHubLogger(LogLevel.Information, LogLevel.Information, "UKHO.TestClass", fakeEventHubLog);
            IEnumerable <KeyValuePair <string, object> > structuredData =
                new FormattedLogValues("Message with {Property1} and {Property1} and a escaped C# keyword name {@var}", "Value 1", "Value 2", "Var value");

            eventHubLogger.Log(LogLevel.Information, 123, structuredData, null, (s, e) => string.Join(",", s.Select(kv => $"{kv.Key}:{kv.Value}")));

            CollectionAssert.DoesNotContain(loggedEntry.LogProperties.Keys, "MessageTemplate");
            CollectionAssert.Contains(loggedEntry.LogProperties.Keys, "Property1");
            CollectionAssert.AreEqual(new[] { "Value 1", "Value 2" }.ToList(), loggedEntry.LogProperties["Property1"] as IEnumerable);
            Assert.AreEqual("Var value", loggedEntry.LogProperties["var"]);
            Assert.AreEqual("Message with {Property1} and {Property1} and a escaped C# keyword name {@var}", loggedEntry.MessageTemplate);
        }
Beispiel #20
0
        public bool IsCompatibleWith(string site, ClientVersion version)
        {
            if (requiredVersion.IsCompatibleWith(version))
            {
                return(true);
            }

            if (logger.IsEnabled(notificationsLevel))
            {
                lock (notificationsLock)
                {
                    if (notifiedSites.Add(site))
                    {
                        var log = new FormattedLogValues("Incompatibility with site \"{0}\". Site version: {1}, required version: {2}", site, version, requiredVersion);
                        logger.Log(notificationsLevel, 0, log, null, (t, e) => t.ToString());
                    }
                }
            }
            return(false);
        }
Beispiel #21
0
        public void Log(LogEvent @event)
        {
            if (@event is null)
            {
                return;
            }

            if (!IsEnabledFor(@event.Level))
            {
                return;
            }

            var logLevel = ConvertLogLevel(@event.Level);

            var message = settings.UseVostokTemplate
                ? LogEventFormatter.Format(@event, Template)
                : LogMessageFormatter.Format(@event);

            var state = new FormattedLogValues(message, Array.Empty <object>());

            logger.Log(logLevel, NullEventId, state, @event.Exception, MessageFormatter);
        }
Beispiel #22
0
        public void LogValues_WithNullAndEnumerable_IsNotMutatingParameter()
        {
            string format = "TestMessage {Param1} {Param2} {Param3} {Param4}";
            int    param1 = 1;
            string param2 = null;

            int[]  param3 = new[] { 1, 2, 3, 4 };
            string param4 = "string";

            var logValues = new FormattedLogValues(format, param1, param2, param3, param4);

            logValues.ToString();

            var state = logValues.ToArray();

            Assert.Equal(new[]
            {
                new KeyValuePair <string, object>("Param1", param1),
                new KeyValuePair <string, object>("Param2", param2),
                new KeyValuePair <string, object>("Param3", param3),
                new KeyValuePair <string, object>("Param4", param4),
                new KeyValuePair <string, object>("{OriginalFormat}", format),
            }, state);
        }
        private static bool messageMatches(string expectedMessage, FormattedLogValues formattedLogValues)
        {
            // separate method as opposed to lambda for easier debugging

            return(formattedLogValues.ToString() == expectedMessage);
        }
Beispiel #24
0
            public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
            {
                var message = new FormattedLogValues(formatter.Invoke(state, exception));

                _testOutputHelper.WriteLine($"{logLevel} - {eventId} - {message}");
            }
        public void LogValues_WithNulls(string expected, string format, object[] args)
        {
            var logValues = new FormattedLogValues(format, args);

            Assert.Equal(expected, logValues.ToString());
        }
        public void FormatsEnumerableValues(string messageFormat, object[] arguments, string expected)
        {
            var logValues = new FormattedLogValues(messageFormat, arguments);

            Assert.Equal(expected, logValues.ToString());
        }
        public static object[] GetValues(this FormattedLogValues lv)
        {
            var field = lv.GetType().GetField("_values", BindingFlags.NonPublic | BindingFlags.Instance);

            return((object[])field.GetValue(lv));
        }
 /// <summary>  Replaces the values in the FormattedLogValues instance.</summary>
 /// <param name="lv">The FormattedLogValues instance.</param>
 /// <param name="values">The values.</param>
 /// <returns></returns>
 public static FormattedLogValues SetValues(this FormattedLogValues lv, params object[] values)
 {
     return(new FormattedLogValues(lv.GetOriginalValue(), values));
 }
Beispiel #29
0
 private static string FormatMessage(FormattedLogValues state, Exception error)
 {
     return(state.ToString());
 }
 /// <summary>Sets a simple value.</summary>
 /// <param name="original">The original.</param>
 /// <param name="value">The value.</param>
 /// <returns></returns>
 public static FormattedLogValues SetSimpleValue(this FormattedLogValues original, string value)
 {
     return(new FormattedLogValues(value));
 }