Пример #1
0
        /// <summary>
        /// Enrich the log event with the current ASP.NET user name, if User.Identity.IsAuthenticated is true.</summary>
        /// <param name="logEvent">The log event to enrich.</param>
        /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent == null) 
                throw new ArgumentNullException("logEvent");

            var userName = _noneUsername;

            if (HttpContext.Current != null)
            {
                var context = new HttpContextWrapper(HttpContext.Current);

                if (context.User != null)
                {
                    if (context.User.Identity == null || context.User.Identity.IsAuthenticated == false)
                    {
                        if (_anonymousUsername != null)
                            userName = _anonymousUsername;
                    }
                    else
                    {
                        userName = context.User.Identity.Name;
                    }
                }
            }

            if (userName == null) 
                return;

            var userNameProperty = new LogEventProperty(UserNamePropertyName, new ScalarValue(userName));
            logEvent.AddPropertyIfAbsent(userNameProperty);
        }
Пример #2
0
        IEnumerable<LogEventProperty> ConstructPositionalProperties(MessageTemplate template, object[] messageTemplateParameters)
        {
            var positionalProperties = template.PositionalProperties;

            if (positionalProperties.Length != messageTemplateParameters.Length)
                SelfLog.WriteLine("Positional property count does not match parameter count: {0}", template);

            var result = new LogEventProperty[messageTemplateParameters.Length];
            foreach (var property in positionalProperties)
            {
                int position;
                if (property.TryGetPositionalValue(out position))
                {
                    if (position < 0 || position >= messageTemplateParameters.Length)
                        SelfLog.WriteLine("Unassigned positional value {0} in: {1}", position, template);
                    else
                        result[position] = ConstructProperty(property, messageTemplateParameters[position]);
                }
            }

            var next = 0;
            for (var i = 0; i < result.Length; ++i)
            {
                if (result[i] != null)
                {
                    result[next] = result[i];
                    ++next;
                }
            }

            if (next != result.Length)
                Array.Resize(ref result, next);

            return result;
        }
        public void LogEventPropertyStructuralEqualityComparerWorksForScalars()
        {
            var scalarStringA = new LogEventProperty("a", new ScalarValue("a"));
            var scalarStringAStructurallyEqual = new LogEventProperty("a", new ScalarValue("a"));

            var scalarStringB = new LogEventProperty("b", new ScalarValue("b"));
            var scalarStringBStructurallyNotEqual = new LogEventProperty("b", new ScalarValue("notEqual"));

            var scalarIntA1 = new LogEventProperty("a", new ScalarValue(1));
            var scalarIntA1StructurallyEqual = new LogEventProperty("a", new ScalarValue(1));
            var scalarIntA1DiffValueSameType = new LogEventProperty("a", new ScalarValue(0));
            var scalarIntB1 = new LogEventProperty("b", new ScalarValue(1));

            var guid1 = Guid.NewGuid();
            var guid2 = Guid.NewGuid();
            var scalarGuid1 = new LogEventProperty("1", new ScalarValue(guid1));
            var scalarGuid1StructurallyEqual = new LogEventProperty("1", new ScalarValue(guid1));
            var scalarGuid1StructurallyNotEqual = new LogEventProperty("1", new ScalarValue("notEqual"));
            var scalarGuid2 = new LogEventProperty("2", new ScalarValue(guid2));

            var sut = new LogEventPropertyStructuralEqualityComparer();

            Assert.True(sut.Equals(scalarStringA, scalarStringAStructurallyEqual));
            Assert.True(sut.Equals(scalarIntA1, scalarIntA1StructurallyEqual));
            Assert.True(sut.Equals(scalarGuid1, scalarGuid1StructurallyEqual));

            Assert.False(sut.Equals(scalarStringB, scalarStringBStructurallyNotEqual));
            Assert.False(sut.Equals(scalarIntA1, scalarIntB1));
            Assert.False(sut.Equals(scalarIntA1, scalarIntA1DiffValueSameType));

            Assert.False(sut.Equals(scalarGuid1, scalarGuid2));
            Assert.False(sut.Equals(scalarGuid1, scalarGuid1StructurallyNotEqual));
        }
        public void LogEventPropertyStructuralEqualityComparerWorksForSequences()
        {
            var intStringDoubleScalarArray =
                new[] { new ScalarValue(1), new ScalarValue("2"), new ScalarValue(3.0), };

            var intStringFloatScalarArray =
                new[] { new ScalarValue("1"), new ScalarValue(2), new ScalarValue(3.0f), };

            var sequenceOfScalarsIntStringDoubleA = new LogEventProperty("a", new SequenceValue(intStringDoubleScalarArray));

            var sequenceOfScalarsIntStringDoubleAStructurallyEqual = new LogEventProperty("a",
                new SequenceValue(new[] { new ScalarValue(1), new ScalarValue("2"), new ScalarValue(3.0), }));

            var sequenceOfScalarsIntStringDoubleAStructurallyNotEqual = new LogEventProperty("a",
                new SequenceValue(new [] { new ScalarValue(1), new ScalarValue("2"), new ScalarValue(3.1), }));

            var sequenceOfScalarsIntStringFloatA = new LogEventProperty("a", new ScalarValue(intStringFloatScalarArray));

            var sequenceOfScalarsIntStringDoubleB = new LogEventProperty("b", new SequenceValue(intStringDoubleScalarArray));

            var sut = new LogEventPropertyStructuralEqualityComparer();

            // Structurally equal
            Assert.True(sut.Equals(sequenceOfScalarsIntStringDoubleA, sequenceOfScalarsIntStringDoubleAStructurallyEqual));

            // Not equal due to having a different property name (but otherwise structurally equal)
            Assert.False(sut.Equals(sequenceOfScalarsIntStringDoubleA, sequenceOfScalarsIntStringDoubleB));

            // Structurally not equal because element 3 has a different value
            Assert.False(sut.Equals(sequenceOfScalarsIntStringDoubleA, sequenceOfScalarsIntStringDoubleAStructurallyNotEqual));

            // Strucrtually not equal because element 3 has a different underlying value and type
            Assert.False(sut.Equals(sequenceOfScalarsIntStringDoubleA, sequenceOfScalarsIntStringFloatA));
        }
Пример #5
0
        /// <summary>
        /// Enrich the log event.
        /// </summary>
        /// <param name="logEvent">The log event to enrich.</param>
        /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
#if !ASPNETCORE50
            _cachedProperty = _cachedProperty ?? propertyFactory.CreateProperty(MachineNamePropertyName, Environment.MachineName);
#else
            _cachedProperty = _cachedProperty ?? propertyFactory.CreateProperty(MachineNamePropertyName, Environment.GetEnvironmentVariable("COMPUTERNAME"));
#endif
            logEvent.AddPropertyIfAbsent(_cachedProperty);
        }
Пример #6
0
        /// <summary>
        /// Enrich the log event with an id assigned to the currently-executing HTTP request, if any.
        /// </summary>
        /// <param name="logEvent">The log event to enrich.</param>
        /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent == null) throw new ArgumentNullException("logEvent");

            if (HttpContext.Current == null)
                return;

            var serviceProvider = (IServiceProvider)HttpContext.Current;
            var workerReqest = (HttpWorkerRequest)serviceProvider.GetService(typeof(HttpWorkerRequest));
            var requestId = workerReqest.RequestTraceIdentifier;

            var requestIdProperty = new LogEventProperty(HttpRequestTraceIdPropertyName, new ScalarValue(requestId));
            logEvent.AddPropertyIfAbsent(requestIdProperty);
        }
Пример #7
0
        /// <summary>
        /// Enrich the log event with the current ASP.NET session id, if sessions are enabled.</summary>
        /// <param name="logEvent">The log event to enrich.</param>
        /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent == null) throw new ArgumentNullException("logEvent");

            if (HttpContext.Current == null)
                return;

            if (HttpContext.Current.Session == null)
                return;

            var sessionId = HttpContext.Current.Session.SessionID;
            var sesionIdProperty = new LogEventProperty(HttpSessionIdPropertyName, new ScalarValue(sessionId));
            logEvent.AddPropertyIfAbsent(sesionIdProperty);
        }
        /// <summary>
        /// Enrich the log event.
        /// </summary>
        /// <param name="logEvent">The log event to enrich.</param>
        /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent == null) throw new ArgumentNullException("logEvent");

            if (HttpContextCurrent.Request == null)
                return;

            if (string.IsNullOrWhiteSpace(HttpContextCurrent.Request.UserHostName))
                return;
            
            var userHostName = HttpContextCurrent.Request.UserHostName;
            var httpRequestClientHostnameProperty = new LogEventProperty(HttpRequestClientHostNamePropertyName, new ScalarValue(userHostName));
            logEvent.AddPropertyIfAbsent(httpRequestClientHostnameProperty);
        }
Пример #9
0
        public void ADictionaryWithScalarKeySerializesAsAnObject()
        {
            var dictKey = Some.Int();
            var dictValue = Some.Int();
            var dict = new DictionaryValue(new Dictionary<ScalarValue, LogEventPropertyValue> {
                { new ScalarValue(dictKey), new ScalarValue(dictValue) }
            });
            var dictProp = new LogEventProperty(Some.String(), dict);
            var @event = Some.InformationEvent();
            @event.AddOrUpdateProperty(dictProp);

            var formatted = FormatToJson(@event);
            var expected = $"{{\"{dictKey}\":{dictValue}}}";
            Assert.True(formatted.Contains(expected));
        }
Пример #10
0
        /// <summary>
        /// Enrich the log event with an id assigned to the currently-executing HTTP request, if any.
        /// </summary>
        /// <param name="logEvent">The log event to enrich.</param>
        /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent == null) throw new ArgumentNullException("logEvent");

            if (HttpContext.Current == null)
                return;

            Guid requestId;
            var requestIdItem = HttpContext.Current.Items[RequestIdItemName];
            if (requestIdItem == null)
                HttpContext.Current.Items[RequestIdItemName] = requestId = Guid.NewGuid();
            else
                requestId = (Guid)requestIdItem;

            var requestIdProperty = new LogEventProperty(HttpRequestIdPropertyName, new ScalarValue(requestId));
            logEvent.AddPropertyIfAbsent(requestIdProperty);
        }
Пример #11
0
        /// <summary>
        /// Enrich the log event.
        /// </summary>
        /// <param name="logEvent">The log event to enrich.</param>
        /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent == null) throw new ArgumentNullException("logEvent");

            if (HttpContext.Current == null)
                return;

            if (HttpContextCurrent.Request == null)
                return;

            if (HttpContextCurrent.Request.UrlReferrer == null)
                return;

            var requestUrlReferrer = HttpContextCurrent.Request.UrlReferrer.ToString();
            var httpRequestUrlReferrerProperty = new LogEventProperty(HttpRequestUrlReferrerPropertyName, new ScalarValue(requestUrlReferrer));
            logEvent.AddPropertyIfAbsent(httpRequestUrlReferrerProperty);
        }
        /// <summary>
        /// Enrich the log event.
        /// </summary>
        /// <param name="logEvent">The log event to enrich.</param>
        /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent == null) throw new ArgumentNullException("logEvent");

            if (HttpContext.Current == null)
                return;

            if (HttpContextCurrent.Request == null)
                return;

            if (string.IsNullOrWhiteSpace(HttpContextCurrent.Request.RawUrl))
                return;

            var requestRawUrl = HttpContextCurrent.Request.RawUrl;
            var httpRequestRawUrlProperty = new LogEventProperty(HttpRequestRawUrlPropertyName, new ScalarValue(requestRawUrl));
            logEvent.AddPropertyIfAbsent(httpRequestRawUrlProperty);
        }
Пример #13
0
        /// <summary>
        /// Enrich the log event with the number assigned to the currently-executing HTTP request, if any.
        /// </summary>
        /// <param name="logEvent">The log event to enrich.</param>
        /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent == null) throw new ArgumentNullException("logEvent");

            if (HttpContext.Current == null)
                return;

            int requestNumber;
            var requestNumberItem = HttpContext.Current.Items[RequestNumberItemName];
            if (requestNumberItem == null)
                HttpContext.Current.Items[RequestNumberItemName] = requestNumber = Interlocked.Increment(ref LastRequestNumber);
            else
                requestNumber = (int)requestNumberItem;

            var requestNumberProperty = new LogEventProperty(HttpRequestNumberPropertyName, new ScalarValue(requestNumber));
            logEvent.AddPropertyIfAbsent(requestNumberProperty);
        }
Пример #14
0
        IEnumerable<LogEventProperty> ConstructNamedProperties(MessageTemplate template, object[] messageTemplateParameters)
        {
            var namedProperties = template.NamedProperties;

            var matchedRun = namedProperties.Length;
            if (namedProperties.Length != messageTemplateParameters.Length)
            {
                matchedRun = Math.Min(namedProperties.Length, messageTemplateParameters.Length);
                SelfLog.WriteLine("Named property count does not match parameter count: ", template);
            }

            var result = new LogEventProperty[matchedRun];
            for (var i = 0; i < matchedRun; ++i)
            {
                var property = template.NamedProperties[i];
                var value = messageTemplateParameters[i];
                result[i] = ConstructProperty(property, value);
            }

            return result;
        }
Пример #15
0
 /// <summary>
 /// Enrich the log event.
 /// </summary>
 /// <param name="logEvent">The log event to enrich.</param>
 /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
 public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
 {
     _cachedProperty = _cachedProperty ?? propertyFactory.CreateProperty(TagPropertyName, TagPropertyValue);
     logEvent.AddPropertyIfAbsent(_cachedProperty);
 }
Пример #16
0
 static void Render(TextWriter output, LogEventProperty property, IFormatProvider formatProvider = null)
 {
     output.Write(property.Name);
     output.Write(": ");
     property.Value.Render(output, null, formatProvider);
 }
Пример #17
0
 public FixedPropertyEnricher(LogEventProperty logEventProperty)
 {
     if (logEventProperty == null) throw new ArgumentNullException(nameof(logEventProperty));
     _logEventProperty = logEventProperty;
 }
 /// <summary>
 /// Enrich the log event.
 /// </summary>
 /// <param name="logEvent">The log event to enrich.</param>
 /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
 public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
 {
     _cachedProperty = _cachedProperty ?? propertyFactory.CreateProperty(EnvironmentUserNamePropertyName, GetEnvironmentUserName());
     logEvent.AddPropertyIfAbsent(_cachedProperty);
 }
Пример #19
0
 /// <summary>
 /// Enrich the log event.
 /// </summary>
 /// <param name="logEvent">The log event to enrich.</param>
 /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
 public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
 {
     _cachedProperty = _cachedProperty ?? propertyFactory.CreateProperty(MachineNamePropertyName, Environment.MachineName);
     logEvent.AddPropertyIfAbsent(_cachedProperty);
 }
Пример #20
0
 private static void Render(TextWriter output, LogEventProperty property)
 {
     output.Write(property.Name);
     output.Write(": ");
     property.Value.Render(output);
 }
Пример #21
0
 /// <summary>
 /// Enrich the log event.
 /// </summary>
 /// <param name="logEvent">The log event to enrich.</param>
 /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
 public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
 {
     _cachedProperty = _cachedProperty ?? propertyFactory.CreateProperty(ProcessIdPropertyName, Process.GetCurrentProcess().Id);
     logEvent.AddPropertyIfAbsent(_cachedProperty);
 }
Пример #22
0
 private static void Render(TextWriter output, LogEventProperty property)
 {
     output.Write(property.Name);
     output.Write(": ");
     property.Value.Render(output);
 }
Пример #23
0
        IEnumerable<LogEventProperty> ConstructNamedProperties(MessageTemplate template, object[] messageTemplateParameters)
        {
            var namedProperties = template.NamedProperties;
            if (namedProperties == null)
                return Enumerable.Empty<LogEventProperty>();

            var matchedRun = namedProperties.Length;
            if (namedProperties.Length != messageTemplateParameters.Length)
            {
                matchedRun = Math.Min(namedProperties.Length, messageTemplateParameters.Length);
                SelfLog.WriteLine("Named property count does not match parameter count: {0}", template);
            }

            var result = new LogEventProperty[messageTemplateParameters.Length];
            for (var i = 0; i < matchedRun; ++i)
            {
                var property = template.NamedProperties[i];
                var value = messageTemplateParameters[i];
                result[i] = ConstructProperty(property, value);
            }

            for (var i = matchedRun; i < messageTemplateParameters.Length; ++i)
            {
                var value = _valueConverter.CreatePropertyValue(messageTemplateParameters[i]);
                result[i] = new LogEventProperty("__" + i, value);
            }
            return result;
        }
Пример #24
0
 static void Render(TextWriter output, LogEventProperty property, IFormatProvider formatProvider = null)
 {
     output.Write(property.Name);
     output.Write(": ");
     property.Value.Render(output, null, formatProvider);
 }
 public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
 {
     var environmentVariable = this.GetType().Assembly.GetName().Version;
     _cachedProperty = _cachedProperty ?? propertyFactory.CreateProperty(AssemblyVersionPropertyName, environmentVariable);
     logEvent.AddPropertyIfAbsent(_cachedProperty);
 }
Пример #26
0
 /// <summary>
 /// Add a property to the event if not already present. 
 /// </summary>
 /// <param name="property">The property to add.</param>
 /// <exception cref="ArgumentNullException"></exception>
 public void AddPropertyIfAbsent(LogEventProperty property)
 {
     if (property == null) throw new ArgumentNullException("property");
     if (!_properties.ContainsKey(property.Name))
         _properties.Add(property.Name, property.Value);
 }
        /// <summary>
        /// Enrich the log event.
        /// </summary>
        /// <param name="logEvent">The log event to enrich.</param>
        /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent == null) throw new ArgumentNullException("logEvent");

            if (HttpContext.Current == null)
                return;

            if (HttpContextCurrent.Request == null)
                return;

            if (string.IsNullOrWhiteSpace(HttpContextCurrent.Request.UserHostAddress))
                return;

            string userHostAddress;

            // Taking Proxy/-ies into consideration, too (if wanted and available)
            if (CheckForHttpProxies)
            {
                userHostAddress = !string.IsNullOrWhiteSpace(HttpContextCurrent.Request.ServerVariables["HTTP_X_FORWARDED_FOR"])
                ? HttpContextCurrent.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
                : HttpContextCurrent.Request.UserHostAddress;
            }
            else
            {
                userHostAddress = HttpContextCurrent.Request.UserHostAddress;
            }

            if (string.IsNullOrWhiteSpace(userHostAddress))
                return;

            // As multiple proxies can be in place according to header spec (see http://en.wikipedia.org/wiki/X-Forwarded-For), we check for it and only extract the first address (which 'should' be the actual client one)
            if (userHostAddress.Contains(","))
            {
                userHostAddress = userHostAddress.Split(',').First().Trim();
            }

            var httpRequestClientHostIPProperty = new LogEventProperty(HttpRequestClientHostIPPropertyName, new ScalarValue(userHostAddress));
            logEvent.AddPropertyIfAbsent(httpRequestClientHostIPProperty);
        }
Пример #28
0
 /// <summary>
 /// Add a property to the event if not already present, otherwise, update its value. 
 /// </summary>
 /// <param name="property">The property to add or update.</param>
 /// <exception cref="ArgumentNullException"></exception>
 public void AddOrUpdateProperty(LogEventProperty property)
 {
     if (property == null) throw new ArgumentNullException("property");
     _properties[property.Name] = property.Value;
 }
        public void AStructureSerializesAsAnObject()
        {
            var value = Some.Int();
            var memberProp = new LogEventProperty(Some.String(), new ScalarValue(value));
            var structure = new StructureValue(new[] { memberProp });
            var structureProp = new LogEventProperty(Some.String(), structure);
            var @event = Some.LogEvent();
            @event.AddOrUpdateProperty(structureProp);

            var formatted = FormatJson(@event);
            var result = (int)formatted.Properties[structureProp.Name][memberProp.Name];
            Assert.AreEqual(value, result);
        }