private void FormatInternal(LogEvent logEvent, TextWriter output)
 {
     if (logEvent == null)
         throw new ArgumentNullException("logEvent");
     if (output == null)
         throw new ArgumentNullException("output");
     if (!_omitEnclosingObject)
         output.Write("{");
     var precedingDelimiter1 = "";
     WriteJsonProperty("Timestamp", logEvent.Timestamp, ref precedingDelimiter1, output);
     WriteJsonProperty("Level", logEvent.Level, ref precedingDelimiter1, output);
     WriteJsonProperty("Message", logEvent.RenderMessage(), ref precedingDelimiter1, output);
     WriteJsonProperty("MessageTemplate", logEvent.MessageTemplate.Text, ref precedingDelimiter1, output);
     if (logEvent.Exception != null)
         WriteJsonProperty("Exception", logEvent.Exception, ref precedingDelimiter1, output);
     if (logEvent.Properties.Count != 0)
     {
         output.Write(",\"Properties\":{");
         var precedingDelimiter2 = "";
         foreach (KeyValuePair<string, LogEventPropertyValue> keyValuePair in logEvent.Properties)
             WriteJsonProperty(keyValuePair.Key, keyValuePair.Value, ref precedingDelimiter2, output);
         output.Write("}");
     }
     if (_omitEnclosingObject)
         return;
     output.Write("}");
 }
        public void Emit(LogEvent logEvent)
        {
            var correctedLogEvent = logEvent;
            if (logEvent.Properties.ContainsKey(Common.Constants.KeyPassportTimestamp))
            {
                var passportTimestampProperty = logEvent.Properties[Common.Constants.KeyPassportTimestamp];
                if (passportTimestampProperty != null)
                {
                    var passportTimestampValue = passportTimestampProperty as ScalarValue;
                    if (passportTimestampValue != null)
                    {
                        if (passportTimestampValue.Value is DateTimeOffset)
                        {
                            var passportTimestamp = (DateTimeOffset)passportTimestampValue.Value;
                            correctedLogEvent = new LogEvent(passportTimestamp
                                                                , logEvent.Level
                                                                , logEvent.Exception
                                                                , logEvent.MessageTemplate
                                                                , logEvent.Properties.Select(x => new LogEventProperty(x.Key, x.Value)).ToList()
                                                                );
                            correctedLogEvent.RemovePropertyIfPresent(Common.Constants.KeyPassportTimestamp);
                        }
                    }
                }
            }

            _destination.Write(correctedLogEvent);
        }
        public void Enrich(LogEvent logEvent)
        {
            if (logEvent == null) throw new ArgumentNullException("logEvent");

            if (HttpContext.Current == null)
                return;

            int requestId;
            var requestIdItem = HttpContext.Current.Items[RequestIdItemName];
            if (requestIdItem == null)
                HttpContext.Current.Items[RequestIdItemName] = requestId = Interlocked.Increment(ref LastRequestId);
            else
                requestId = (int)requestIdItem;

            string sessionId = null;
            if (HttpContext.Current.Session != null)
                sessionId = HttpContext.Current.Session.SessionID;

            logEvent.AddPropertyIfAbsent(
                LogEventProperty.For(HttpRequestPropertyName,
                new
                {
                    SessionId = sessionId,
                    Id = requestId,
                },
                destructureObjects: true));
        }
        /// <summary>
        /// Format log events to GoogleCloudPubsub message format
        /// </summary>
        /// <param name="logEvent">Event to format</param>
        /// <param name="output">Output to write event</param>
        public void Format(LogEvent logEvent, TextWriter output)
        {
            // This method is executed each time a log event has to be stored (into memory, into the buffer file, ...)
            // In this development data is stored as raw data: no format is given.
            // Each log is stored in a separate line.

            if (logEvent.Properties != null && logEvent.Properties.Count > 0)
            {
                string value = string.Empty;
                IEnumerator<LogEventPropertyValue> enumer = logEvent.Properties.Values.GetEnumerator();
                enumer.Reset();
                enumer.MoveNext();
                LogEventPropertyValue logvalue = enumer.Current;

                if (logvalue != null)
                {
                    value = logvalue.ToString();
                    if (value.StartsWith("\"") && value.Length > 2)
                    {
                        value = value.Substring(1, value.Length - 2);
                    }
                }

                //*************************
                output.WriteLine(value);
                //*************************
            }
            else
            {
                //*************************
                output.WriteLine(logEvent.MessageTemplate.Text);
                //*************************
            }
        }
        public void IndexDecider_EndsUpInTheOutput()
        {
            //DO NOTE that you cant send objects as scalar values through Logger.*("{Scalar}", {});
            var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
            const string messageTemplate = "{Song}++ @{Complex}";
            var template = new MessageTemplateParser().Parse(messageTemplate);
            _options.IndexDecider = (l, utcTime) => string.Format("logstash-{1}-{0:yyyy.MM.dd}", utcTime, l.Level.ToString().ToLowerInvariant());
            using (var sink = new ElasticsearchSink(_options))
            {
                var properties = new List<LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) };
                var e = new LogEvent(timestamp, LogEventLevel.Information, null, template, properties);
                sink.Emit(e);
                var exception = new ArgumentException("parameter");
                properties = new List<LogEventProperty>
                {
                    new LogEventProperty("Song", new ScalarValue("Old Macabre")),
                    new LogEventProperty("Complex", new ScalarValue(new { A  = 1, B = 2}))
                };
                e = new LogEvent(timestamp.AddYears(-2), LogEventLevel.Fatal, exception, template, properties);
                sink.Emit(e);
            }

            _seenHttpPosts.Should().NotBeEmpty().And.HaveCount(1);
            var json = _seenHttpPosts.First();
            var bulkJsonPieces = json.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            bulkJsonPieces.Should().HaveCount(4);
            bulkJsonPieces[0].Should().Contain(@"""_index"":""logstash-information-2013.05.28");
            bulkJsonPieces[1].Should().Contain("New Macabre");
            bulkJsonPieces[2].Should().Contain(@"""_index"":""logstash-fatal-2011.05.28");
            bulkJsonPieces[3].Should().Contain("Old Macabre");

            //serilog by default simpy .ToString()'s unknown objects
            bulkJsonPieces[3].Should().Contain("Complex\":\"{");

        }
 public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
 {
     if (logEvent == null) throw new ArgumentNullException("logEvent");
     if (propertyFactory == null) throw new ArgumentNullException("propertyFactory");
     var property = propertyFactory.CreateProperty(_name, _value, _destructureObjects);
     logEvent.AddPropertyIfAbsent(property);
 }
        public async Task UsesCustomPropertyNames()
        {
            try
            {
                await this.ThrowAsync();
            }
            catch (Exception e)
            {
                var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
                var messageTemplate = "{Song}++";
                var template = new MessageTemplateParser().Parse(messageTemplate);
                using (var sink = new ElasticsearchSink(_options))
                {
                    var properties = new List<LogEventProperty>
                    {
                        new LogEventProperty("Song", new ScalarValue("New Macabre")), 
                        new LogEventProperty("Complex", new ScalarValue(new { A = 1, B = 2 }))
                    };
                    var logEvent = new LogEvent(timestamp, LogEventLevel.Information, e, template, properties);
                    //one off
                    sink.Emit(logEvent);

                    sink.Emit(logEvent);
                    logEvent = new LogEvent(timestamp.AddDays(2), LogEventLevel.Information, e, template, properties);
                    sink.Emit(logEvent);
                }
                var bulkJsonPieces = this.AssertSeenHttpPosts(_seenHttpPosts, 4);
                bulkJsonPieces[0].Should().Contain(@"""_index"":""logstash-2013.05.28");
                bulkJsonPieces[1].Should().Contain("New Macabre");
                bulkJsonPieces[1].Should().NotContain("Properties\"");
                bulkJsonPieces[1].Should().Contain("fields\":{");
                bulkJsonPieces[1].Should().Contain("@timestamp");
                bulkJsonPieces[2].Should().Contain(@"""_index"":""logstash-2013.05.30");
            }
        }
Beispiel #8
0
        private NLog.LogEventInfo ConvertToNLog(Serilog.Events.LogEvent logEvent)
        {
            var renderSpace = new StringWriter();

            _textFormatter.Format(logEvent, renderSpace);

            var nlogEvent = new NLog.LogEventInfo
            {
                Exception      = logEvent.Exception,
                FormatProvider = null,
                LoggerName     = GetLoggerName(logEvent),
                Message        = renderSpace.ToString(),
                Level          = ConvertToNLogLevel(logEvent.Level),
                TimeStamp      = logEvent.Timestamp.UtcDateTime,
            };

            foreach (var property in logEvent.Properties)
            {
                var sv     = property.Value as ScalarValue;
                var format = (sv != null && sv.Value is string) ? "l" : null;

                nlogEvent.Properties[property.Key] = property.Value.ToString(format, null);
            }

            return(nlogEvent);
        }
Beispiel #9
0
        public void Emit(Serilog.Events.LogEvent logEvent)
        {
            var nlogEvent = ConvertToNLog(logEvent);
            var logger    = GetNLogLogger(nlogEvent.LoggerName);

            logger.Log(nlogEvent);
        }
 public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
 {
     if (logEvent.Exception != null)
     {
         logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("ExceptionDetail", this.DestructureException(logEvent.Exception), true));
     }
 }
        private LogglyEvent CreateLogglyEvent(LogEvent logEvent)
        {
            var logglyEvent = new LogglyEvent();

            var isHttpTransport = LogglyConfig.Instance.Transport.LogTransport == LogTransport.Https;
            logglyEvent.Syslog.Level = ToSyslogLevel(logEvent);

            foreach (var key in logEvent.Properties.Keys)
            {
                var propertyValue = logEvent.Properties[key];
                var simpleValue = LogglyPropertyFormatter.Simplify(propertyValue);
                logglyEvent.Data.AddIfAbsent(key, simpleValue);
            }

            logglyEvent.Data.AddIfAbsent("Message", logEvent.RenderMessage(_formatProvider));

            if (isHttpTransport)
            {
                // syslog will capture these via the header
                logglyEvent.Data.AddIfAbsent("Level", logEvent.Level.ToString());
            }

            if (logEvent.Exception != null)
            {
                logglyEvent.Data.AddIfAbsent("Exception", logEvent.Exception);
            }
            return logglyEvent;
        }
Beispiel #12
0
		public void Emit( LogEvent logEvent )
		{
			var stringWriter = new StringWriter();
			textFormatter.Format( logEvent, stringWriter );
			var message = stringWriter.ToString().Trim();
			Trace.WriteLine( message );
		}
Beispiel #13
0
 internal static void LogEventDoesNotContainCorrelationIdentifiers(Serilog.Events.LogEvent logEvent)
 {
     // Do not assert on the version property
     // Do not assert on the service property
     Assert.False(logEvent.Properties.ContainsKey(CorrelationIdentifier.SpanIdKey));
     Assert.False(logEvent.Properties.ContainsKey(CorrelationIdentifier.TraceIdKey));
 }
        public static void FormatContent(LogEvent logEvent, TextWriter output)
        {
            if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));
            if (output == null) throw new ArgumentNullException(nameof(output));

            output.Write("{\"Timestamp\":\"");
            output.Write(logEvent.Timestamp.ToString("o"));
            output.Write("\",\"Level\":\"");
            output.Write(logEvent.Level);
            output.Write("\",\"MessageTemplate\":");
            JsonValueFormatter.WriteQuotedJsonString(logEvent.MessageTemplate.Text, output);
            if (logEvent.Exception != null)
            {
                output.Write(",\"Exception\":");
                JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), output);
            }

            if (logEvent.Properties.Count != 0)
                WriteProperties(logEvent.Properties, output);

            var tokensWithFormat = logEvent.MessageTemplate.Tokens
                .OfType<PropertyToken>()
                .Where(pt => pt.Format != null);

            if (tokensWithFormat.Any())
                WriteRenderings(tokensWithFormat.GroupBy(pt => pt.PropertyName), logEvent.Properties, output);

            output.Write('}');
        }
        public static void HasPropertyValue(object propertyValue, string propertyName, LogEvent logEvent)
        {
            HasProperty(propertyName, logEvent);

            LogEventPropertyValue value = logEvent.Properties[propertyName];
            Assert.That(value.LiteralValue(), Is.EqualTo(propertyValue), "The property value was not as expected");
        }
 public void Emit(LogEvent logEvent)
 {
     if (logEvent == null) throw new ArgumentNullException("logEvent");
     var sr = new StringWriter();
     _textFormatter.Format(logEvent, sr);
     System.Diagnostics.Trace.Write(sr.ToString());
 }
 public async Task UsesCustomPropertyNames()
 {
     try
     {
         await new HttpClient().GetStringAsync("http://i.do.not.exist");
     }
     catch (Exception e)
     {
         var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
         var messageTemplate = "{Song}++";
         var template = new MessageTemplateParser().Parse(messageTemplate);
         using (var sink = new ElasticsearchSink(_options))
         {
             var properties = new List<LogEventProperty>
             {
                 new LogEventProperty("Song", new ScalarValue("New Macabre")), 
                 new LogEventProperty("Complex", new ScalarValue(new { A = 1, B = 2 }))
             };
             var logEvent = new LogEvent(timestamp, LogEventLevel.Information, e, template, properties);
             sink.Emit(logEvent);
             logEvent = new LogEvent(timestamp.AddDays(2), LogEventLevel.Information, e, template, properties);
             sink.Emit(logEvent);
         }
         _seenHttpPosts.Should().NotBeEmpty().And.HaveCount(1);
         var json = _seenHttpPosts.First();
         var bulkJsonPieces = json.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
         bulkJsonPieces.Should().HaveCount(4);
         bulkJsonPieces[0].Should().Contain(@"""_index"":""logstash-2013.05.28");
         bulkJsonPieces[1].Should().Contain("New Macabre");
         bulkJsonPieces[1].Should().NotContain("Properties\"");
         bulkJsonPieces[1].Should().Contain("fields\":{");
         bulkJsonPieces[1].Should().Contain("@timestamp");
         bulkJsonPieces[2].Should().Contain(@"""_index"":""logstash-2013.05.30");
     }
 }
        /// <summary>
        /// Format the log event into the output.
        /// </summary>
        /// <param name="logEvent">The event to format.</param>
        /// <param name="output">The output.</param>
        public void Format(LogEvent logEvent, TextWriter output)
        {
            if (logEvent == null) throw new ArgumentNullException("logEvent");
            if (output == null) throw new ArgumentNullException("output");

            if (!_omitEnclosingObject)
                output.Write("{");

            var delim = "";
            WriteJsonProperty("TimeStamp", logEvent.TimeStamp, ref delim, output);
            WriteJsonProperty("Level", logEvent.Level, ref delim, output);
            WriteJsonProperty("MessageTemplate", logEvent.MessageTemplate, ref delim, output);

            if (logEvent.Exception != null)
                WriteJsonProperty("Exception", logEvent.Exception, ref delim, output);

            if (logEvent.Properties.Count != 0)
            {
                output.Write(",\"Properties\":{");
                var pdelim = "";
                foreach (var property in logEvent.Properties.Values)
                {
                    WriteJsonProperty(property.Name, property.Value, ref pdelim, output);
                }
                output.Write("}");
            }

            if (!_omitEnclosingObject)
                output.Write("}");
        }
Beispiel #19
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);
        }
 static string FormatToJson(LogEvent @event)
 {
     var formatter = new JsonFormatter();
     var output = new StringWriter();
     formatter.Format(@event, output);
     return output.ToString();
 }
Beispiel #21
0
        /// <summary>
        /// Emit the provided log event to the sink.
        /// </summary>
        /// <param name="logEvent">The log event to write.</param>
        public void Emit(LogEvent logEvent)
        {
            var category = "info";
            switch (logEvent.Level)
            {
                case LogEventLevel.Verbose:
                case LogEventLevel.Debug:
                    category = "verbose";
                    break;
                case LogEventLevel.Information:
                    category = "info";
                    break;
                case LogEventLevel.Warning:
                    category = "warning";
                    break;
                case LogEventLevel.Error:
                case LogEventLevel.Fatal:
                    category = "error";
                    break;
                default:
                    SelfLog.WriteLine("Unexpected logging level, writing to loggly as Info");

                    break;
            }

            var properties = logEvent.Properties
                         .Select(pv => new { Name = pv.Key, Value = LogglyPropertyFormatter.Simplify(pv.Value) })
                         .ToDictionary((a) => a.Name, b => b.Value);

            if (logEvent.Exception != null)
                properties.Add("Exception", (object)logEvent.Exception);

            _client.Log(logEvent.RenderMessage(_formatProvider), category, properties);
        }
 /// <summary>
 /// Format the log event into the output.
 /// </summary>
 /// <param name="logEvent">The event to format.</param>
 /// <param name="output">The output.</param>
 public void Format(LogEvent logEvent, TextWriter output)
 {
     if (logEvent == null) throw new ArgumentNullException("logEvent");
     if (output == null) throw new ArgumentNullException("output");
     var outputProperties = OutputProperties.GetOutputProperties(logEvent);
     _outputTemplate.Render(outputProperties, output, _formatProvider);
 }
Beispiel #23
0
		/// <summary>
		/// Emit the provided log event to the sink.
		/// </summary>
		/// <param name="logEvent">The log event to write.</param>
		/// <remarks>
		/// <see cref="LogEventLevel.Debug" />, <see cref="LogEventLevel.Information" /> and <see cref="LogEventLevel.Verbose" /> are registered as <see cref="EventLogEntryType.Information" />.
		/// <see cref="LogEventLevel.Error" />, <see cref="LogEventLevel.Fatal" /> are registered as <see cref="EventLogEntryType.Error" />.
		/// <see cref="LogEventLevel.Warning" /> are registered as <see cref="EventLogEntryType.Warning" />.
		/// The Event ID in the Windows log will be set to the integer value of the <paramref name="logEvent"/>'s <see cref="LogEvent.Level"/> property, so that the log can be filtered with more granularity.</remarks>
		public void Emit(LogEvent logEvent)
		{
			if (logEvent == null) throw new ArgumentNullException("logEvent");

			EventLogEntryType type;
			switch (logEvent.Level)
			{
				case LogEventLevel.Debug:
				case LogEventLevel.Information:
				case LogEventLevel.Verbose:
					type = EventLogEntryType.Information;
					break;

				case LogEventLevel.Error:
				case LogEventLevel.Fatal:
					type = EventLogEntryType.Error;
					break;

				case LogEventLevel.Warning:
					type = EventLogEntryType.Warning;
					break;

				default:
					SelfLog.WriteLine("Unexpected logging level, writing to EventLog as Information");
					type = EventLogEntryType.Information;
					break;
			}

			var payload = new StringWriter();
			_textFormatter.Format(logEvent, payload);

			System.Diagnostics.EventLog.WriteEntry(_source, payload.ToString(), type, (int)logEvent.Level);
		}
Beispiel #24
0
 public void Emit(LogEvent logEvent)
 {
     if (logEvent == null) throw new ArgumentNullException("logEvent");
     var renderSpace = new StringWriter();
     _textFormatter.Format(logEvent, renderSpace);
     Console.WriteLine (renderSpace.ToString ());
 }
        /// <summary>
        /// Emit the provided log event to the sink.
        /// </summary>
        /// <param name="logEvent">The log event to write.</param>
        public void Emit(LogEvent logEvent)
        {
            var renderedMessage = logEvent.RenderMessage(_formatProvider);
            
            // take logEvent and use it for the corresponding ITelemetry counterpart
            if (logEvent.Exception != null)
            {
                var exceptionTelemetry = new ExceptionTelemetry(logEvent.Exception)
                {
                    SeverityLevel = logEvent.Level.ToSeverityLevel(),
                    HandledAt = ExceptionHandledAt.UserCode,
                    Timestamp = logEvent.Timestamp
                };
                
                // write logEvent's .Properties to the AI one
                ForwardLogEventPropertiesToTelemetryProperties(exceptionTelemetry, logEvent, renderedMessage);

                _telemetryClient.TrackException(exceptionTelemetry);
            }
            else
            {
                var eventTelemetry = new EventTelemetry(logEvent.MessageTemplate.Text)
                {
                    Timestamp = logEvent.Timestamp
                };
                
                // write logEvent's .Properties to the AI one
                ForwardLogEventPropertiesToTelemetryProperties(eventTelemetry, logEvent, renderedMessage);
                
                _telemetryClient.TrackEvent(eventTelemetry);
            }
        }
Beispiel #26
0
        public void Emit(LogEvent logEvent)
        {
            var messageBroker = _messageBrokerFactory();
            if (messageBroker == null)
                return;

            messageBroker.Publish(new LogEventMessage(logEvent, _formatProvider));
        }
        public void Emit(LogEvent logEvent)
        {
            var sr = new StringWriter();
            formatter.Format(logEvent, sr);
            var text = sr.ToString().Trim();

            Debug.WriteLine(text);
        }
        public void SetUp()
        {
            var delegatingSink = new DelegatingSink(evt => { _loggedEvent = evt; });
            var logger = new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.Sink(delegatingSink).CreateLogger();

            _loggedEvent = null;
            _traceListener = new global::SerilogTraceListener.SerilogTraceListener(logger);
        }
Beispiel #29
0
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var testProperties = TestContext.CurrentContext?.Test.Properties;
            if (testProperties == null) return;
            if (!testProperties.Contains("TestId")) return;

            logEvent.AddOrUpdateProperty(propertyFactory.CreateProperty("TestId", new ScalarValue(testProperties["TestId"])));
        }
Beispiel #30
0
 public void Emit(LogEvent logEvent)
 {
     if (logEvent == null) throw new ArgumentNullException("logEvent");
     lock (_syncRoot)
     {
         _textFormatter.Format(logEvent, _textWriter);
     }
 }
        /// <summary>
        /// Format log events to GoogleCloudPubsub message format
        /// </summary>
        /// <param name="logEvent">Event to format</param>
        /// <param name="output">Output to write event</param>
        public void Format(LogEvent logEvent, TextWriter output)
        {
            // This method is executed each time a log event has to be stored (into memory, into the buffer file, ...)
            // In this development data is stored as raw data: no format is given.
            // Each log is stored in a separate line.

            output.WriteLine(logEvent.MessageTemplate.Text);
        }
Beispiel #32
0
        public void Enrich(Serilog.Events.LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var traceId       = StringUtil.DecodeBase64ToUTF8(_httpContextAccessor.HttpContext.Request.Headers[Constants.TraceIdHeader].ToString());
            var userSessionId = StringUtil.DecodeBase64ToUTF8(_httpContextAccessor.HttpContext.Request.Headers[Constants.UserSessionIdHeader].ToString());

            logEvent.AddPropertyIfAbsent(new LogEventProperty("TraceId", new ScalarValue(traceId)));
            logEvent.AddPropertyIfAbsent(new LogEventProperty("UserSessionId", new ScalarValue(userSessionId)));
        }
Beispiel #33
0
 /// <summary>
 /// Emit the provided log event to the sink.
 /// </summary>
 /// <param name="logEvent">The log event to write.</param>
 public void Emit(LogEvent logEvent)
 {
     if (logEvent == null)
         throw new ArgumentNullException(nameof(logEvent));
     var renderSpace = new StringWriter();
     _textFormatter.Format(logEvent, renderSpace);
     System.Diagnostics.Debug.WriteLine(renderSpace.ToString());
 }
        public void Should_copy_properties_not_present_in_message_template()
        {
            var serilogEvent = new SerilogEvent(DateTimeOffset.Now, SerilogLevel.Information, null,
                                                new MessageTemplate("Hello!", Enumerable.Empty <MessageTemplateToken>()),
                                                new [] { new LogEventProperty("A", new ScalarValue(1)), new LogEventProperty("B", new ScalarValue(2)) });

            serilogLogger.Write(serilogEvent);

            var vostokEvent = observedEvents.Single();

            vostokEvent.Properties?["A"].Should().Be(1);
            vostokEvent.Properties?["B"].Should().Be(2);
        }
Beispiel #35
0
        private static string GetLoggerName(Serilog.Events.LogEvent logEvent)
        {
            var loggerName = DefaultLoggerName;

            LogEventPropertyValue sourceContext;

            if (logEvent.Properties.TryGetValue(Constants.SourceContextPropertyName, out sourceContext))
            {
                var sv = sourceContext as ScalarValue;
                if (sv != null && sv.Value is string)
                {
                    loggerName = (string)sv.Value;
                }
            }

            return(loggerName);
        }
Beispiel #36
0
        internal static void Contains(Serilog.Events.LogEvent logEvent, string service, string version, string env, ulong traceId, ulong spanId)
        {
            Assert.True(logEvent.Properties.ContainsKey(CorrelationIdentifier.ServiceKey));
            Assert.Equal(service, logEvent.Properties[CorrelationIdentifier.ServiceKey].ToString().Trim(new[] { '\"' }), ignoreCase: true);

            Assert.True(logEvent.Properties.ContainsKey(CorrelationIdentifier.VersionKey));
            Assert.Equal(version, logEvent.Properties[CorrelationIdentifier.VersionKey].ToString().Trim(new[] { '\"' }), ignoreCase: true);

            Assert.True(logEvent.Properties.ContainsKey(CorrelationIdentifier.EnvKey));
            Assert.Equal(env, logEvent.Properties[CorrelationIdentifier.EnvKey].ToString().Trim(new[] { '\"' }), ignoreCase: true);

            Assert.True(logEvent.Properties.ContainsKey(CorrelationIdentifier.TraceIdKey));
            Assert.Equal(traceId, ulong.Parse(logEvent.Properties[CorrelationIdentifier.TraceIdKey].ToString().Trim(new[] { '\"' })));

            Assert.True(logEvent.Properties.ContainsKey(CorrelationIdentifier.SpanIdKey));
            Assert.Equal(spanId, ulong.Parse(logEvent.Properties[CorrelationIdentifier.SpanIdKey].ToString().Trim(new[] { '\"' })));
        }
        public void Should_copy_primary_simple_components_of_log_events(SerilogLevel serilogLevel, LogLevel vostokLevel)
        {
            var serilogEvent = new SerilogEvent(
                DateTimeOffset.Now,
                serilogLevel,
                new Exception("I have failed.."),
                new MessageTemplate("Hello!", Enumerable.Empty <MessageTemplateToken>()),
                Enumerable.Empty <LogEventProperty>());

            serilogLogger.Write(serilogEvent);

            var vostokEvent = observedEvents.Single();

            vostokEvent.Level.Should().Be(vostokLevel);
            vostokEvent.Timestamp.Should().Be(serilogEvent.Timestamp);
            vostokEvent.MessageTemplate.Should().Be("Hello!");
            vostokEvent.Exception.Should().BeSameAs(serilogEvent.Exception);
            vostokEvent.Properties.Should().BeEmpty();
        }
        public void TestSetup()
        {
            outputBuilder = new StringBuilder();
            outputWriter  = new StringWriter(outputBuilder);

            observedEvent = null;

            serilogLevelSwitch = new LoggingLevelSwitch(SerilogLevel.Verbose);

            serilogLogger = new LoggerConfiguration()
                            .WriteTo.TextWriter(outputWriter, outputTemplate: "{Message}")
                            .MinimumLevel.ControlledBy(serilogLevelSwitch)
                            .Filter.ByExcluding(
                evt =>
            {
                observedEvent = evt;
                return(false);
            })
                            .CreateLogger();

            adapter = new SerilogLog(serilogLogger);
        }
Beispiel #39
0
        public void Emit(Serilog.Events.LogEvent logEvent)
        {
            var loggerName = GetLoggerName(logEvent);
            var logger     = GetLogrilaLogger(loggerName);

            var renderSpace = new StringWriter();

            _textFormatter.Format(logEvent, renderSpace);

            if (logEvent.Level == LogEventLevel.Verbose)
            {
                logger.Trace(renderSpace.ToString());
            }
            else if (logEvent.Level == LogEventLevel.Debug)
            {
                logger.Debug(renderSpace.ToString());
            }
            else if (logEvent.Level == LogEventLevel.Information)
            {
                logger.Info(renderSpace.ToString());
            }
            else if (logEvent.Level == LogEventLevel.Warning)
            {
                logger.Warn(renderSpace.ToString());
            }
            else if (logEvent.Level == LogEventLevel.Error)
            {
                logger.Error(renderSpace.ToString());
            }
            else if (logEvent.Level == LogEventLevel.Fatal)
            {
                logger.Fatal(renderSpace.ToString());
            }
            else
            {
                throw new NotSupportedException("Level " + logEvent.Level + " is currently not supported.");
            }
        }
Beispiel #40
0
 internal static void LogEventContains(Serilog.Events.LogEvent logEvent, string service, string version, string env, Scope scope)
 {
     Contains(logEvent, service, version, env, scope.Span.TraceId, scope.Span.SpanId);
 }
Beispiel #41
-1
        public void Emit(LogEvent logEvent)
        {
            var loggerName = "Default";

            LogEventPropertyValue sourceContext;
            if (logEvent.Properties.TryGetValue(Constants.SourceContextPropertyName, out sourceContext))
            {
                var sv = sourceContext as ScalarValue;
                if (sv?.Value is string)
                {
                    loggerName = (string) sv.Value;
                }
            }

            var level = MapLogLevel(logEvent);
            var message = logEvent.RenderMessage(_formatProvider);
            var exception = logEvent.Exception;

            var nlogEvent = new LogEventInfo(level, loggerName, message)
            {
                Exception = exception
            };

            foreach (var property in logEvent.Properties)
            {
                var sv = property.Value as ScalarValue;
                var format = (sv?.Value is string) ? "l" : null;

                nlogEvent.Properties[property.Key] = property.Value.ToString(format, null);
            }

            var logger = LogManager.GetLogger(loggerName);
            logger.Log(nlogEvent);
        }