public void WithToStringSelectedShouldRespectFormatPassed()
        {
            const string PropertyName = "TestProperty";

            const string PropertyValue = "TestValue";

            var property = new LogEventProperty(PropertyName, new ScalarValue(PropertyValue));

            var writer = new SinglePropertyColumnWriter(PropertyName, PropertyWriteMethod.ToString, format: "l");

            var testEvent = new LogEvent(
                DateTime.Now,
                LogEventLevel.Debug,
                null,
                new MessageTemplate(Enumerable.Empty <MessageTemplateToken>()),
                new[] { property });

            var result = writer.GetValue(testEvent);

            Assert.Equal(PropertyValue, result);
        }
Exemple #2
0
        public void Enrich(HttpContext context, LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (context.Response.StatusCode < 400)
            {
                return;
            }

            if (!_allowedContentTypes.Contains(context.Request.ContentType))
            {
                return;
            }

            var bodyStream = new StreamReader(context.Request.Body);
            var bodyText   = bodyStream.ReadToEnd();

            bodyText = RequestBodyFilter.Get(bodyText);

            var bodyProperty = new LogEventProperty("Body", new ScalarValue(bodyText));

            logEvent.AddPropertyIfAbsent(bodyProperty);
        }
        public override void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            base.Enrich(logEvent, propertyFactory);

            if (_serviceName == null)
            {
                _serviceName = propertyFactory.CreateProperty("ServiceName", Context.ServiceName);
            }
            if (_partitionId == null)
            {
                _partitionId = propertyFactory.CreateProperty("PartitionId", Context.PartitionId);
            }
            if (_applicationName == null)
            {
                _applicationName = propertyFactory.CreateProperty("ApplicationName", Context.CodePackageActivationContext.ApplicationName);
            }

            logEvent.AddPropertyIfAbsent(_serviceName);
            logEvent.AddPropertyIfAbsent(_partitionId);
            logEvent.AddPropertyIfAbsent(_applicationName);
        }
Exemple #4
0
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            // the settings might not have a path or we might not be within a command in which case
            // we won't have the setting so a default value for the log file will be required
            LogEventProperty logFilePathProperty;

            if (_cachedLogFilePathProperty != null && Path.Equals(_cachedLogFilePath))
            {
                // Path hasn't changed, so let's use the cached property
                logFilePathProperty = _cachedLogFilePathProperty;
            }
            else
            {
                // We've got a new path for the log. Let's create a new property
                // and cache it for future log events to use
                _cachedLogFilePath         = Path;
                _cachedLogFilePathProperty = logFilePathProperty = propertyFactory.CreateProperty(LogFilePathPropertyName, Path);
            }

            logEvent.AddPropertyIfAbsent(logFilePathProperty);
        }
        /// <summary>
        /// Enrich LogEvent message with provided CorrelationId or generate a new one for this HTTP request.
        /// </summary>
        /// <param name="logEvent">&gt;Log Event</param>
        /// <param name="propertyFactory">Serilog Property Factory</param>
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent == null)
            {
                throw new ArgumentNullException("logEvent");
            }
            if (propertyFactory == null)
            {
                throw new ArgumentNullException("propertyFactory");
            }
            if (string.IsNullOrWhiteSpace(_serviceName))
            {
                if (string.IsNullOrWhiteSpace(_serviceName))
                {
                    _serviceName = "N/A";
                }
            }
            LogEventProperty property = propertyFactory.CreateProperty("Service", _serviceName, false);

            logEvent.AddOrUpdateProperty(property);
        }
        public void RawSelectedForScalarPropertyShouldReturnPropertyValue()
        {
            const string PropertyName = "TestProperty";

            const int PropertyValue = 42;

            var property = new LogEventProperty(PropertyName, new ScalarValue(PropertyValue));

            var writer = new SinglePropertyColumnWriter(PropertyName, PropertyWriteMethod.Raw);

            var testEvent = new LogEvent(
                DateTime.Now,
                LogEventLevel.Debug,
                null,
                new MessageTemplate(Enumerable.Empty <MessageTemplateToken>()),
                new[] { property });

            var result = writer.GetValue(testEvent);

            Assert.Equal(PropertyValue, result);
        }
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent == null)
            {
                throw new ArgumentNullException(nameof(logEvent));
            }

            if (propertyFactory == null)
            {
                throw new ArgumentNullException(nameof(propertyFactory));
            }

            Murmur32 murmur = MurmurHash.Create32();

            byte[]           bytes           = Encoding.UTF8.GetBytes(logEvent.MessageTemplate.Text);
            byte[]           hash            = murmur.ComputeHash(bytes);
            string           hexadecimalHash = BitConverter.ToString(hash).Replace("-", "");
            LogEventProperty eventId         = propertyFactory.CreateProperty("EventType", hexadecimalHash);

            logEvent.AddPropertyIfAbsent(eventId);
        }
Exemple #8
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 (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);
        }
        /// <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 sessionIdProperty = new LogEventProperty(HttpSessionIdPropertyName, new ScalarValue(sessionId));

            logEvent.AddPropertyIfAbsent(sessionIdProperty);
        }
        /// <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);
        }
 private LogEventProperty GetLogEventProperty(ILogEventPropertyFactory propertyFactory, string propertyName)
 {
     if (propertyName == OSPropertyName)
     {
         if (_cachedOSProperty == null)
         {
             _cachedOSProperty = CreateOSProperty(propertyFactory);
         }
         return(_cachedOSProperty);
     }
     else if (propertyName == LinuxVersionPropertyName)
     {
         if (_cachedLinuxProperty == null)
         {
             _cachedLinuxProperty = CreateLinuxVersionProperty(propertyFactory);
         }
         return(_cachedLinuxProperty);
     }
     else
     {
         throw new InvalidOperationException("Invalid PropertyName");
     }
 }
Exemple #12
0
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent.Exception == null)
            {
                return;
            }

            var exception = logEvent.Exception.GetBaseException();

            if (exception.Data == null || exception.Data.Count == 0)
            {
                return;
            }

            var data = exception.Data
                       .Cast <DictionaryEntry>()
                       .Where(e => e.Key is string)
                       .Select(e => propertyFactory.CreateProperty((string)e.Key, e.Value));

            var property = new LogEventProperty("ExceptionData", new StructureValue(data));

            logEvent.AddPropertyIfAbsent(property);
        }
        /// <summary>
        ///     Enrich the log event with found by name claim's value
        /// </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(nameof(logEvent));
            }

            if (HttpContext.Current == null)
            {
                return;
            }

            if (HttpContextCurrent.Request == null)
            {
                return;
            }

            var user = HttpContext.Current.User;

            if (user == null)
            {
                return;
            }

            var claims = ((ClaimsIdentity)user.Identity).Claims;

            var value = claims?.FirstOrDefault(c => c.Type == _claimProperty)?.Value;

            if (string.IsNullOrWhiteSpace(value))
            {
                return;
            }

            var claimProperty = new LogEventProperty(_logEventProperty, new ScalarValue(value));

            logEvent.AddPropertyIfAbsent(claimProperty);
        }
Exemple #14
0
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent == null)
            {
                throw new ArgumentNullException(nameof(logEvent));
            }
            var context = HttpContext.Current;

            var userId = logEvent.Properties.ContainsKey("UserId")
                ? logEvent.Properties["UserId"].ToString()
                : context?.User.Claims?.FirstOrDefault(c => c.Type == "UserId")?.Value;

            var userIdProperty = new LogEventProperty("UserId", new ScalarValue(userId));

            logEvent.AddPropertyIfAbsent(userIdProperty);

            var transactionId = logEvent.Properties.ContainsKey("TransactionId")
                ? logEvent.Properties["TransactionId"].ToString()
                : context?.TraceIdentifier;

            var transactionIdProperty = new LogEventProperty("TransactionId", new ScalarValue(transactionId));

            logEvent.AddPropertyIfAbsent(transactionIdProperty);
        }
Exemple #15
0
        /// <summary>
        /// Enrich LogEvent message with provided CorrelationId or generate a new one for this HTTP request.
        /// </summary>
        /// <param name="logEvent">Log Event</param>
        /// <param name="propertyFactory">Serilog Property Factory</param>
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent == null)
            {
                throw new ArgumentNullException(nameof(logEvent));
            }

            if (propertyFactory == null)
            {
                throw new ArgumentNullException(nameof(propertyFactory));
            }

            if (string.IsNullOrWhiteSpace(_serviceName))
            {
                if (string.IsNullOrWhiteSpace(_serviceName))
                {
                    _serviceName = "N/A";
                }
            }

            LogEventProperty property = propertyFactory.CreateProperty(LoggingConstants.ServiceNamePropertiesName, _serviceName, false);

            logEvent.AddOrUpdateProperty(property);
        }
 /// <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);
 }
 public static string AsString(this LogEventProperty property)
 {
     return(property.Value.AsString());
 }
Exemple #18
0
 public bool BindProperty(string propertyName, object value, bool destructureObjects, out LogEventProperty property)
 {
     property = null;
     return(false);
 }
Exemple #19
0
        /// <summary>
        /// Uses configured scalar conversion and destructuring rules to bind a property value to its captured
        /// representation.
        /// </summary>
        /// <returns>True if the property could be bound, otherwise false (<summary>Logger</summary>
        /// <param name="propertyName">The name of the property. Must be non-empty.</param>
        /// <param name="value">The property value.</param>
        /// <param name="destructureObjects">If true, the value will be serialized as a structured
        /// object if possible; if false, the object will be recorded as a scalar or simple array.</param>
        /// <param name="property">The resulting property.</param>
        /// methods never throw exceptions).</returns>
        public bool BindProperty(string propertyName, object value, bool destructureObjects, out LogEventProperty property)
        {
            if (!LogEventProperty.IsValidName(propertyName))
            {
                property = null;
                return(false);
            }

            property = _messageTemplateProcessor.CreateProperty(propertyName, value, destructureObjects);
            return(true);
        }
        public bool BindProperty(string propertyName, object value, bool destructureObjects, out LogEventProperty property)
        {
            if (_frozen)
            {
                return(_logger.BindProperty(propertyName, value, destructureObjects, out property));
            }

            lock (_sync)
            {
                return(_logger.BindProperty(propertyName, value, destructureObjects, out property));
            }
        }
        internal bool InvokeBindProperty(ILogger root, ILogger cached, IReloadableLogger caller, string propertyName,
                                         object propertyValue, bool destructureObjects, out LogEventProperty property,
                                         out bool canBind, out ILogger newRoot, out ILogger newCached, out bool frozen)
        {
            if (_frozen)
            {
                var(logger, update) = UpdateForCaller(root, cached, caller, out newRoot, out newCached, out frozen);
                canBind             = logger.BindProperty(propertyName, propertyValue, destructureObjects, out property);
                return(update);
            }

            lock (_sync)
            {
                var(logger, update) = UpdateForCaller(root, cached, caller, out newRoot, out newCached, out frozen);
                canBind             = logger.BindProperty(propertyName, propertyValue, destructureObjects, out property);
                return(update);
            }
        }
Exemple #22
0
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var property = new LogEventProperty("ServiceName", new ScalarValue(_serviceName.Value));

            logEvent.AddPropertyIfAbsent(property);
        }
Exemple #23
0
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var property = new LogEventProperty("MessageId", new ScalarValue(_messageId));

            logEvent.AddPropertyIfAbsent(property);
        }
 public FixedPropertyEnricher(LogEventProperty property)
 {
     _property = property;
 }
Exemple #25
0
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var property = new LogEventProperty("LogType", new ScalarValue("Queue"));

            logEvent.AddPropertyIfAbsent(property);
        }
 public bool BindProperty(string propertyName, object value, bool destructureObjects, out LogEventProperty property)
 {
     return(this.logger.BindProperty(propertyName, value, destructureObjects, out property));
 }
Exemple #27
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);
 }
Exemple #28
0
 public bool BindProperty(string propertyName, object value, bool destructureObjects, out LogEventProperty property)
 {
     throw new NotImplementedException();
 }
 /// <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(ProcessNamePropertyName, System.Diagnostics.Process.GetCurrentProcess().ProcessName);
     logEvent.AddPropertyIfAbsent(_cachedProperty);
 }
        /// <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(Ec2InstanceIdPropertyName, Ec2InstanceMetadata.GetProperty("/instance-id"));

            logEvent.AddPropertyIfAbsent(_cachedProperty);
        }