public void Format(LogEvent logEvent, TextWriter output)
        {
            if (logEvent == null)
            {
                throw new ArgumentNullException(nameof(logEvent));
            }

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

            output.Write("{");

            var precedingDelimiter = string.Empty;

            //Write(TIMESTAMP_FIELD, logEvent.Timestamp.DateTime.ToString("o"));                    // Local Time
            Write(TIMESTAMP_FIELD, logEvent.Timestamp.ToUniversalTime().DateTime.ToString("o"));    // Convert to UTC

            Write(LEVEL_FIELD, logEvent.Level.ToString());
            Write(MESSAGE_FIELD, logEvent.RenderMessage());

            if (logEvent.Exception != null)
            {
                Write(EXCEPTION_FIELD, logEvent.Exception.ToString());
            }

            if (logEvent.Properties.Any())
            {
                output.Write(precedingDelimiter);
                WriteProperties(logEvent.Properties, output);
                precedingDelimiter = COMMA_DELIMITER;
            }

            output.Write("}");

            void Write(string name, string value)
            {
                output.Write(precedingDelimiter);
                precedingDelimiter = COMMA_DELIMITER;
                JsonValueFormatter.WriteQuotedJsonString(name, output);
                output.Write(":");
                JsonValueFormatter.WriteQuotedJsonString(value, output);
            }
        }
Example #2
0
        /// <summary>
        /// Format the log event into the output.
        /// </summary>
        /// <param name="logEvent">The event to format.</param>
        /// <param name="output">The output.</param>
        /// <param name="valueFormatter">A value formatter for <see cref="LogEventPropertyValue"/>s on the event.</param>
        public static void FormatEvent(LogEvent logEvent, TextWriter output, JsonValueFormatter valueFormatter)
        {
            if (logEvent == null)
            {
                throw new ArgumentNullException(nameof(logEvent));
            }
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }
            if (valueFormatter == null)
            {
                throw new ArgumentNullException(nameof(valueFormatter));
            }

            // DateTime
            output.Write("{\"dt\":\"");
            output.Write(logEvent.Timestamp.UtcDateTime.ToString("O"));

            // Level
            output.Write("\",\"lv\":\"");
            output.Write(_levelMap[(int)logEvent.Level]);

            // Message Template
            output.Write("\",\"mt\":");
            JsonValueFormatter.WriteQuotedJsonString(logEvent.MessageTemplate.Text, output);

            // Exception
            if (logEvent.Exception != null)
            {
                output.Write(",\"ex\":");
                JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), output);
            }

            // Other Properties
            foreach (var property in logEvent.Properties)
            {
                output.Write(',');
                JsonValueFormatter.WriteQuotedJsonString(property.Key, output);
                output.Write(':');
                valueFormatter.Format(property.Value, output);
            }

            output.Write('}');
        }
        static void WriteProperties(IReadOnlyDictionary <string, LogEventPropertyValue> properties, TextWriter output)
        {
            output.Write(",\"Properties\":{");

            var precedingDelimiter = "";

            foreach (var property in properties)
            {
                output.Write(precedingDelimiter);
                precedingDelimiter = ",";

                JsonValueFormatter.WriteQuotedJsonString(property.Key, output);
                output.Write(':');
                ValueFormatter.Format(property.Value, output);
            }

            output.Write('}');
        }
        private static bool WriteArrays(string delimiter, string parent, List <KeyValuePair <string, LogEventPropertyValue> > properties,
                                        TextWriter output)
        {
            var fullParent = string.IsNullOrEmpty(parent) ? "xXx" : parent + ".";

            foreach (var arraySet in properties.GroupBy(g => g.Key.Replace(fullParent, "")
                                                        .Substring(0, g.Key.Replace(fullParent, "").IndexOf('['))))
            {
                var property = arraySet.First();

                output.Write(delimiter);
                delimiter = ",";

                JsonValueFormatter.WriteQuotedJsonString(arraySet.Key.ToUnderscoreCase(), output);
                output.Write(':');
                output.Write('[');
                var itemsDelimiter = "";

                var objectKey = fullParent +
                                property.Key.Replace(fullParent, "")
                                .Substring(0, property.Key
                                           .Replace(fullParent, "")
                                           .IndexOf(']'));
                var objectArray = arraySet.Where(x => x.Key.StartsWith(objectKey)).ToList();
                if (objectArray.Count > 1)
                {
                    WriteChildren(delimiter, objectKey + "]", objectArray, output);
                    output.Write(']');
                    continue;
                }

                foreach (var item in arraySet.AsEnumerable())
                {
                    output.Write(itemsDelimiter);
                    itemsDelimiter = ",";
                    ValueFormatter.Instance.Format(item.Value, output);
                }

                output.Write(']');
            }

            return(delimiter != "");
        }
Example #5
0
        private static void WriteProperties(
            IReadOnlyDictionary <string, LogEventPropertyValue> properties,
            TextWriter output)
        {
            if (properties.Any <KeyValuePair <string, LogEventPropertyValue> >())
            {
                output.Write(",");
            }
            string str = "";

            foreach (KeyValuePair <string, LogEventPropertyValue> property in (IEnumerable <KeyValuePair <string, LogEventPropertyValue> >)properties)
            {
                output.Write(str);
                str = ",";
                JsonValueFormatter.WriteQuotedJsonString(property.Key[0].ToString().ToLower() + property.Key.Substring(1), output);
                output.Write(':');
                CustomLogstashJsonFormatter.ValueFormatter.Format(property.Value, output);
            }
        }
Example #6
0
        public void Format(LogEvent logEvent, TextWriter output)
        {
            output.Write("{");
            output.Write($"\"{RequestProperties.TIMESTAMP_UTC}\":\"{logEvent.Timestamp.ToUniversalTime().DateTime:u}\"");
            output.Write($",\"{RequestProperties.DATE}\":\"{logEvent.Timestamp.ToUniversalTime().DateTime:yyyy-MM-dd}\"");
            output.Write($",\"{RequestProperties.LEVEL}\":\"{logEvent.Level.ToString()}\"");

            if (logEvent.Properties.TryGetValue(RequestProperties.EVENT_ID, out var eventId))
            {
                output.Write(",");
                JsonValueFormatter.WriteQuotedJsonString(RequestProperties.EVENT_ID, output);
                output.Write(":");
                _formatter.Format(eventId, output);
            }

            output.Write($",\"{RequestProperties.MESSAGE_TEMPLATE}\":\"{logEvent.MessageTemplate}\"");

            output.Write(",\"RenderedMessage\":");
            var message = logEvent.MessageTemplate.Render(logEvent.Properties);

            JsonValueFormatter.WriteQuotedJsonString(message, output);

            if (logEvent.Exception != null)
            {
                output.Write(",");
                JsonValueFormatter.WriteQuotedJsonString("Exception", output);
                output.Write(":");
                JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), output);
            }

            output.Write($"\"{RequestProperties.PROPERTIES}\":{{");

            foreach (var property in logEvent.Properties)
            {
                output.Write(",");
                JsonValueFormatter.WriteQuotedJsonString(property.Key.Pascalize(), output);
                output.Write(":");
                _formatter.Format(property.Value, output);
            }

            output.Write("}}");
            output.WriteLine();
        }
Example #7
0
        private static void Format(LogEvent logEvent, TextWriter output, JsonValueFormatter valueFormatter)
        {
            if (logEvent is null)
            {
                throw new ArgumentNullException(nameof(logEvent));
            }

            if (output is null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            output.Write(@"{""timestamp"":""");
            output.Write(logEvent.Timestamp.UtcDateTime.ToString("O"));
            output.Write(@""",""message"":");
            JsonValueFormatter.WriteQuotedJsonString(logEvent.MessageTemplate.Render(logEvent.Properties), output);

            output.Write(@",""level"":""");
            output.Write(logEvent.Level);
            output.Write('"');

            if (logEvent.Exception != null)
            {
                output.Write(@",""exception"":");
                JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), output);
            }

            foreach (var(key, value) in logEvent.Properties)
            {
                var str = key;
                if (str.Length > 0 && str[0] == '@')
                {
                    str = "@" + str;
                }
                output.Write(',');
                JsonValueFormatter.WriteQuotedJsonString(str, output);
                output.Write(':');
                valueFormatter.Format(value, output);
            }

            output.Write('}');
        }
        private static void WriteProperties(IReadOnlyDictionary <string, LogEventPropertyValue> properties, TextWriter output)
        {
            if (properties.Any())
            {
                output.Write(",");
            }

            var precedingDelimiter = "";

            foreach (var property in properties)
            {
                output.Write(precedingDelimiter);
                precedingDelimiter = ",";

                var camelCasePropertyKey = property.Key[0].ToString().ToLower() + property.Key.Substring(1);
                JsonValueFormatter.WriteQuotedJsonString(camelCasePropertyKey, output);
                output.Write(':');
                ValueFormatter.Format(property.Value, output);
            }
        }
        static void FlattenAndWriteStructure(StructureValue structure, TextWriter output, ref string precedingDelimiter)
        {
            foreach (var property in structure.Properties)
            {
                var nestedStructure = property.Value as StructureValue;
                if (nestedStructure != null)
                {
                    FlattenAndWriteStructure(nestedStructure, output, ref precedingDelimiter);
                }
                else
                {
                    output.Write(precedingDelimiter);
                    precedingDelimiter = ",";

                    JsonValueFormatter.WriteQuotedJsonString(property.Name, output);
                    output.Write(':');
                    ValueFormatter.Format(property.Value, output);
                }
            }
        }
Example #10
0
        private void WriteFormattedJsonData(string key, object value, TextWriter output)
        {
            if (string.IsNullOrEmpty(key))
            {
                return;
            }

            output.Write(JsonDelim);
            JsonValueFormatter.WriteQuotedJsonString(key, output);
            output.Write(JsonColon);

            if (value == null)
            {
                _valueFormatter.Format(JsonNull, output);
            }
            else
            {
                JsonValueFormatter.WriteQuotedJsonString(value.ToString(), output);
            }
        }
Example #11
0
        private 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 (IsRenderingMessage)
            {
                output.Write(",\"RenderedMessage\":");

                var message = logEvent.MessageTemplate.Render(logEvent.Properties);
                JsonValueFormatter.WriteQuotedJsonString(message, output);
            }

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

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

            output.Write('}');
        }
Example #12
0
        private 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.UtcDateTime.ToString("o"));

            output.Write("\",\"LogLevel\":\"");
            output.Write(logEvent.Level);

            output.Write("\",\"Message\":");
            var message = logEvent.MessageTemplate.Render(logEvent.Properties);

            JsonValueFormatter.WriteQuotedJsonString(message.Replace("\"", ""), output);

            if (logEvent.Exception != null)
            {
                var innermostException = GetInnermostException(logEvent.Exception);

                output.Write(",\"ErrorMessage\":");
                output.Write($"\"{innermostException.Message}\"");

                WriteCustomInnermostException(innermostException, ",", output);
            }

            output.Write(",");

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

            output.Write('}');
        }
        /// <summary>
        /// Construct a <see cref="SplunkJsonFormatter"/>.
        /// </summary>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="renderTemplate">If true, the template used will be rendered and written to the output as a property named MessageTemplate</param>
        /// <param name="index">The Splunk index to log to</param>
        /// <param name="source">The source of the event</param>
        /// <param name="sourceType">The source type of the event</param>
        /// <param name="host">The host of the event</param>
        public SplunkJsonFormatter(
            bool renderTemplate,
            IFormatProvider formatProvider,
            string source,
            string sourceType,
            string host,
            string index)
        {
            _renderTemplate = renderTemplate;
            _formatProvider = formatProvider;

            var suffixWriter = new StringWriter();

            suffixWriter.Write("}"); // Terminates "event"

            if (!string.IsNullOrWhiteSpace(source))
            {
                suffixWriter.Write(",\"source\":");
                JsonValueFormatter.WriteQuotedJsonString(source, suffixWriter);
            }

            if (!string.IsNullOrWhiteSpace(sourceType))
            {
                suffixWriter.Write(",\"sourceType\":");
                JsonValueFormatter.WriteQuotedJsonString(sourceType, suffixWriter);
            }

            if (!string.IsNullOrWhiteSpace(host))
            {
                suffixWriter.Write(",\"host\":");
                JsonValueFormatter.WriteQuotedJsonString(host, suffixWriter);
            }

            if (!string.IsNullOrWhiteSpace(index))
            {
                suffixWriter.Write(",\"index\":");
                JsonValueFormatter.WriteQuotedJsonString(index, suffixWriter);
            }
            suffixWriter.Write('}'); // Terminates the payload
            _suffix = suffixWriter.ToString();
        }
        private void WriterException(Exception exception, string precedingDelimiter, TextWriter output)
        {
            if (exception != null)
            {
                output.Write(precedingDelimiter);

                output.Write("\"Exception\":{");

                JsonValueFormatter.WriteQuotedJsonString("Message", output);
                output.Write(':');
                JsonValueFormatter.WriteQuotedJsonString(exception.Message, output);

                output.Write(",");

                JsonValueFormatter.WriteQuotedJsonString("StackTrace", output);
                output.Write(':');
                JsonValueFormatter.WriteQuotedJsonString(exception.StackTrace, output);

                output.Write('}');
            }
        }
Example #15
0
        protected override int VisitDictionaryValue(ThemedValueFormatterState state, DictionaryValue dictionary)
        {
            var count = 0;

            using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref count))
                state.Output.Write('{');

            var delim = string.Empty;

            foreach (var element in dictionary.Elements)
            {
                if (delim.Length != 0)
                {
                    using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref count))
                        state.Output.Write(delim);
                }

                delim = ", ";

                var style = element.Key.Value == null
                    ? ConsoleThemeStyle.Null
                    : element.Key.Value is string
                            ?ConsoleThemeStyle.String
                            : ConsoleThemeStyle.Scalar;

                using (ApplyStyle(state.Output, style, ref count))
                    JsonValueFormatter.WriteQuotedJsonString((element.Key.Value ?? "null").ToString(), state.Output);

                using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref count))
                    state.Output.Write(": ");

                count += Visit(state.Nest(), element.Value);
            }

            using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref count))
                state.Output.Write('}');

            return(count);
        }
        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('}');
        }
        /// <inheritdoc/>
        public void Format(LogEvent logEvent, TextWriter output)
        {
            if (logEvent == null)
            {
                throw new ArgumentNullException(nameof(logEvent));
            }
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            output.Write("{\"time\":\"");
            output.Write(logEvent.Timestamp.ToEpoch().ToString(CultureInfo.InvariantCulture));
            output.Write("\",\"event\":{\"Level\":\"");
            output.Write(logEvent.Level);
            output.Write('"');

            if (_renderTemplate)
            {
                output.Write(",\"MessageTemplate\":");
                JsonValueFormatter.WriteQuotedJsonString(logEvent.MessageTemplate.Text, output);
            }

            output.Write(",\"RenderedMessage\":");
            JsonValueFormatter.WriteQuotedJsonString(logEvent.RenderMessage(_formatProvider), output);

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

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

            output.WriteLine(_suffix);
        }
        private 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("\",\"app\":\"");
            output.Write(_app);

            if (_env != null)
            {
                output.Write("\",\"env\":\"");
                output.Write(_env);
            }

            output.Write("\",\"line\":");
            var message   = logEvent.MessageTemplate.Render(logEvent.Properties);
            var exception = logEvent.Exception != null ? Environment.NewLine + logEvent.Exception : "";

            JsonValueFormatter.WriteQuotedJsonString(message + exception, output);

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

            output.Write('}');
        }
Example #19
0
        private void WriteCustomInnermostException(Exception exception, string delimiter, TextWriter output)
        {
            var si = new SerializationInfo(exception.GetType(), new FormatterConverter());
            var sc = new StreamingContext();

            exception.GetObjectData(si, sc);

            var stackTrace = si.GetString("StackTraceString");
            var source     = si.GetString("Source");

            output.Write(delimiter);
            JsonValueFormatter.WriteQuotedJsonString("ExceptionName", output);
            output.Write(':');
            JsonValueFormatter.WriteQuotedJsonString(exception.GetType().Name, output);

            output.Write(delimiter);
            JsonValueFormatter.WriteQuotedJsonString("ExceptionSource", output);
            output.Write(':');
            JsonValueFormatter.WriteQuotedJsonString(source, output);

            output.Write(delimiter);
            JsonValueFormatter.WriteQuotedJsonString("StackTrace", output);
            output.Write(':');
            JsonValueFormatter.WriteQuotedJsonString(stackTrace, output);

            output.Write(delimiter);
            JsonValueFormatter.WriteQuotedJsonString("ExceptionSource", output);
            output.Write(':');
            JsonValueFormatter.WriteQuotedJsonString(source, output);

            foreach (DictionaryEntry currentData in exception.Data)
            {
                output.Write(delimiter);
                JsonValueFormatter.WriteQuotedJsonString(currentData.Key.ToString(), output);
                output.Write(':');
                JsonValueFormatter.WriteQuotedJsonString(currentData.Value?.ToString(), output);
            }
        }
Example #20
0
        private static void WriteRenderings(
            IEnumerable <IGrouping <string, PropertyToken> > tokensWithFormat,
            IReadOnlyDictionary <string, LogEventPropertyValue> properties,
            TextWriter output)
        {
            output.Write(",\"Renderings\":{");

            var rdelim = string.Empty;

            foreach (var ptoken in tokensWithFormat)
            {
                output.Write(rdelim);
                rdelim = ",";

                JsonValueFormatter.WriteQuotedJsonString(ptoken.Key, output);
                output.Write(":[");

                var fdelim = string.Empty;
                foreach (var format in ptoken)
                {
                    output.Write(fdelim);
                    fdelim = ",";

                    output.Write("{\"Format\":");
                    JsonValueFormatter.WriteQuotedJsonString(format.Format, output);

                    output.Write(",\"Rendering\":");
                    var sw = new StringWriter();
                    format.Render(properties, sw);
                    JsonValueFormatter.WriteQuotedJsonString(sw.ToString(), output);
                    output.Write('}');
                }

                output.Write(']');
            }

            output.Write('}');
        }
        private static void WriteProperties(
            IReadOnlyDictionary <string, LogEventPropertyValue> properties,
            TextWriter output)
        {
            output.Write('{');

            var precedingDelimiter = "";

            foreach (var property in properties.Where(x => x.Key.IndexOf('[') == -1))
            {
                output.Write(precedingDelimiter);
                precedingDelimiter = ",";

                var key = property.Key.ToUnderscoreCase();
                if (property.Key.ToLower() == "timestamp")
                {
                    key = "@timestamp";
                }

                JsonValueFormatter.WriteQuotedJsonString(key, output);
                output.Write(':');
                ValueFormatter.Instance.Format(property.Value, output);
            }

            foreach (var arraySet in properties.Where(x => x.Key.IndexOf('[') >= 0).GroupBy(g => g.Key.Substring(0, g.Key.IndexOf('['))))
            {
                output.Write(precedingDelimiter);
                precedingDelimiter = ",";

                JsonValueFormatter.WriteQuotedJsonString(arraySet.Key.ToUnderscoreCase(), output);
                output.Write(':');
                output.Write('[');
                WriteArray(arraySet.AsEnumerable(), output);
                output.Write(']');
            }

            output.Write('}');
        }
        /// <summary>
        /// Format the log event into the output.
        /// </summary>
        /// <param name="logEvent">The event to format.</param>
        /// <param name="output">The output.</param>
        /// <param name="valueFormatter">A value formatter for <see cref="LogEventPropertyValue"/>s on the event.</param>
        public static void FormatEvent(LogEvent logEvent, TextWriter output, JsonValueFormatter valueFormatter)
        {
            if (logEvent == null)
            {
                throw new ArgumentNullException(nameof(logEvent));
            }
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }
            if (valueFormatter == null)
            {
                throw new ArgumentNullException(nameof(valueFormatter));
            }

            AppendMessage(logEvent, output);
            AppendMessageTemplate(logEvent, output);
            AppendTimestamp(logEvent, output);
            AppendRenderings(logEvent, output);
            AppendLevel(logEvent, output);

            foreach (var property in logEvent.Properties)
            {
                var name = property.Key;
                if (name.Length > 0 && name[0] == '@')
                {
                    // Escape first '@' by doubling
                    name = '@' + name;
                }

                output.Write(',');
                JsonValueFormatter.WriteQuotedJsonString(name, output);
                output.Write(':');
                valueFormatter.Format(property.Value, output);
            }

            output.Write('}');
        }
        private void WriteProperties(Dictionary <string, LogEventPropertyValue> properties, TextWriter output, Exception exception)
        {
            output.Write(",\"AdditionalData\":{");

            var precedingDelimiter = "";

            if (properties.Count != 0)
            {
                foreach (var property in properties)
                {
                    output.Write(precedingDelimiter);
                    precedingDelimiter = ",";

                    JsonValueFormatter.WriteQuotedJsonString(property.Key, output);
                    output.Write(':');
                    ValueFormatter.Format(property.Value, output);
                }
            }

            WriterException(exception, precedingDelimiter, output);

            output.Write('}');
        }
        /// <summary>
        ///  Rendering x=y properties
        /// These properties have no any children
        /// These properties are not array
        /// </summary>
        /// <param name="delimiter">Json values separator</param>
        /// <param name="parent">Full parents key and dotted format, Such as : Emzam.NewUsers.Registered</param>
        /// <param name="properties">List of leaf children</param>
        /// <param name="output">TextWriter to write json string</param>
        private static bool WriteLeaves(string delimiter, string parent, List <KeyValuePair <string, LogEventPropertyValue> > properties,
                                        TextWriter output)
        {
            var fullParent = string.IsNullOrEmpty(parent) ? "xXx" : parent + ".";

            foreach (var property in properties)
            {
                var key = property.Key.Replace(fullParent, "").ToUnderscoreCase();
                if (key.ToLower() == "timestamp")
                {
                    key = "@timestamp";
                }

                output.Write(delimiter);
                delimiter = ",";

                JsonValueFormatter.WriteQuotedJsonString(key, output);
                output.Write(':');
                ValueFormatter.Instance.Format(property.Value, output);
            }

            return(delimiter != "");
        }
        private static void WriteProperties(
            IReadOnlyDictionary <string, LogEventPropertyValue> properties,
            TextWriter output)
        {
            //output.Write(",\"Properties\":{");

            var precedingDelimiter = "";

            foreach (var property in properties)
            {
                if (string.Equals(property.Key, "HttpContext", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (property.Value is StructureValue sv)
                    {
                        foreach (var prop in sv.Properties)
                        {
                            output.Write(precedingDelimiter);
                            precedingDelimiter = ",";
                            JsonValueFormatter.WriteQuotedJsonString(prop.Name, output);
                            output.Write(':');
                            ValueFormatter.Instance.Format(prop.Value, output);
                        }
                    }
                }
                else
                {
                    output.Write(precedingDelimiter);
                    precedingDelimiter = ",";
                    JsonValueFormatter.WriteQuotedJsonString(property.Key, output);
                    output.Write(':');
                    ValueFormatter.Instance.Format(property.Value, output);
                }
            }

            //output.Write('}');
        }
        private static void AppendRenderings(LogEvent logEvent, TextWriter output)
        {
            var tokensWithFormat = logEvent.MessageTemplate.Tokens
                                   .OfType <PropertyToken>()
                                   .Where(pt => pt.Format != null);

            // Better not to allocate an array in the 99.9% of cases where this is false
            // ReSharper disable once PossibleMultipleEnumeration
            if (tokensWithFormat.Any())
            {
                output.Write(",\"Renderings\":[");
                var delim = "";
                foreach (var r in tokensWithFormat)
                {
                    output.Write(delim);
                    delim = ",";
                    var space = new StringWriter();
                    r.Render(logEvent.Properties, space);
                    JsonValueFormatter.WriteQuotedJsonString(space.ToString(), output);
                }

                output.Write(']');
            }
        }
        private List <global::TencentCloud.Cls.Log.Types.Content> GetLogEventContents(LogEvent logEvent)
        {
            var contents = new List <global::TencentCloud.Cls.Log.Types.Content>();
            var sw1      = new StringWriter();

            contents.Add(new global::TencentCloud.Cls.Log.Types.Content
            {
                Key   = "Timestamp",
                Value = logEvent.Timestamp.ToString("o")
            });
            contents.Add(new global::TencentCloud.Cls.Log.Types.Content
            {
                Key   = "Level",
                Value = logEvent.Level.ToString()
            });
            JsonValueFormatter.WriteQuotedJsonString(logEvent.MessageTemplate.Text, sw1);
            contents.Add(new global::TencentCloud.Cls.Log.Types.Content
            {
                Key   = "MessageTemplate",
                Value = sw1.ToString()
            });
            sw1.Flush();
            var message = logEvent.MessageTemplate.Render(logEvent.Properties);

            JsonValueFormatter.WriteQuotedJsonString(message, sw1);
            contents.Add(new global::TencentCloud.Cls.Log.Types.Content
            {
                Key   = "RenderedMessage",
                Value = sw1.ToString()
            });
            sw1.Flush();
            if (logEvent.Exception != null)
            {
                JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), sw1);
                contents.Add(new global::TencentCloud.Cls.Log.Types.Content
                {
                    Key   = "Exception",
                    Value = sw1.ToString()
                });
            }

            if (logEvent.Properties.Count != 0)
            {
                var sw = new StringWriter();
                WriteProperties(logEvent.Properties, sw);
                contents.Add(new global::TencentCloud.Cls.Log.Types.Content
                {
                    Key   = "Properties",
                    Value = sw.ToString()
                });
            }
            // Better not to allocate an array in the 99.9% of cases where this is false
            var tokensWithFormat = logEvent.MessageTemplate.Tokens
                                   .OfType <PropertyToken>()
                                   .Where(pt => pt.Format != null);

            // ReSharper disable once PossibleMultipleEnumeration
            if (tokensWithFormat.Any())
            {
                var output = new StringWriter();
                // ReSharper disable once PossibleMultipleEnumeration
                WriteRenderings(tokensWithFormat.GroupBy(pt => pt.PropertyName), logEvent.Properties, output);
                contents.Add(new global::TencentCloud.Cls.Log.Types.Content
                {
                    Key   = "Renderings",
                    Value = output.ToString()
                });
            }
            return(contents);
        }
Example #28
0
        public int FormatLiteralValue(ScalarValue scalar, TextWriter output, string format)
        {
            var value = scalar.Value;
            var count = 0;

            if (value == null)
            {
                using (ApplyStyle(output, ConsoleThemeStyle.Null, ref count))
                    output.Write("null");
                return(count);
            }

            if (value is string str)
            {
                using (ApplyStyle(output, ConsoleThemeStyle.String, ref count)) {
                    if (format != "l")
                    {
                        JsonValueFormatter.WriteQuotedJsonString(str, output);
                    }
                    else
                    {
                        output.Write(str);
                    }
                }
                return(count);
            }

            if (value is ValueType)
            {
                if (value is int || value is uint || value is long || value is ulong ||
                    value is decimal || value is byte || value is sbyte || value is short ||
                    value is ushort || value is float || value is double)
                {
                    using (ApplyStyle(output, ConsoleThemeStyle.Number, ref count))
                        scalar.Render(output, format, _formatProvider);
                    return(count);
                }

                if (value is bool b)
                {
                    using (ApplyStyle(output, ConsoleThemeStyle.Boolean, ref count))
                        output.Write(b);

                    return(count);
                }

                if (value is char ch)
                {
                    using (ApplyStyle(output, ConsoleThemeStyle.Scalar, ref count)) {
                        output.Write('\'');
                        output.Write(ch);
                        output.Write('\'');
                    }
                    return(count);
                }
            }

            using (ApplyStyle(output, ConsoleThemeStyle.Scalar, ref count))
                scalar.Render(output, format, _formatProvider);

            return(count);
        }
Example #29
0
        private void FormatContent(LogEvent logEvent, TextWriter output)
        {
            if (logEvent == null)
            {
                throw new ArgumentNullException(nameof(logEvent));
            }
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            output.Write("{\"@t\":\"");
            output.Write(logEvent.Timestamp.UtcDateTime.ToString("o"));

            output.Write("\",\"@mt\":");
            JsonValueFormatter.WriteQuotedJsonString(logEvent.MessageTemplate.Text, output);

            if (IsRenderingMessage)
            {
                output.Write(",\"@m\":");
                var message = logEvent.MessageTemplate.Render(logEvent.Properties);
                JsonValueFormatter.WriteQuotedJsonString(message, output);
            }

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

            // Better not to allocate an array in the 99.9% of cases where this is false
            // ReSharper disable once PossibleMultipleEnumeration
            if (tokensWithFormat.Any())
            {
                output.Write(",\"@r\":[");
                var delim = "";
                foreach (var r in tokensWithFormat)
                {
                    output.Write(delim);
                    delim = ",";
                    var space = new StringWriter();
                    r.Render(logEvent.Properties, space);
                    JsonValueFormatter.WriteQuotedJsonString(space.ToString(), output);
                }
                output.Write(']');
            }

            if (logEvent.Level != LogEventLevel.Information)
            {
                output.Write(",\"@l\":\"");
                output.Write(logEvent.Level);
                output.Write('\"');
            }

            if (logEvent.Exception != null)
            {
                output.Write(",\"@x\":");
                JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), output);
            }

            foreach (var property in logEvent.Properties)
            {
                var name = property.Key;
                if (name.Length > 0 && name[0] == '@')
                {
                    // Escape first '@' by doubling
                    name = '@' + name;
                }

                output.Write(',');
                JsonValueFormatter.WriteQuotedJsonString(name, output);
                output.Write(':');
                ValueFormatter.Instance.Format(property.Value, output);
            }

            output.Write('}');
        }
        /// <summary>
        /// Format the log event into the output.
        /// </summary>
        /// <param name="logEvent">The event to format.</param>
        /// <param name="output">The output.</param>
        /// <param name="valueFormatter">A value formatter for <see cref="LogEventPropertyValue"/>s on the event.</param>
        public void FormatEvent(LogEvent logEvent, TextWriter originalOutput, JsonValueFormatter valueFormatter)
        {
            if (logEvent == null)
            {
                throw new ArgumentNullException(nameof(logEvent));
            }
            if (originalOutput == null)
            {
                throw new ArgumentNullException(nameof(originalOutput));
            }
            if (valueFormatter == null)
            {
                throw new ArgumentNullException(nameof(valueFormatter));
            }

            // wrap the originally text writer in one that can count the number of characters written
            var output = new CountingTextWriter(originalOutput);

            /*
             * 'timestamp', 'message', 'severity' and 'exception' are well-known
             * properties that Stackdriver will use to display and analyse your
             * logs correctly.
             */

            // TIMESTAMP
            output.Write("{\"timestamp\":\"");
            output.Write(logEvent.Timestamp.UtcDateTime.ToString("O"));

            // MESSAGE
            output.Write("\",\"message\":");
            var message = logEvent.MessageTemplate.Render(logEvent.Properties);

            JsonValueFormatter.WriteQuotedJsonString(message, output);

            // FINGERPRINT
            output.Write(",\"fingerprint\":\"");
            var id = EventIdHash.Compute(logEvent.MessageTemplate.Text);

            output.Write(id.ToString("x8"));
            output.Write('"');

            // SEVERITY
            // https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity
            output.Write(",\"severity\":\"");
            var severity = StackDriverLogLevel.GetSeverity(logEvent.Level);

            output.Write(severity);
            output.Write('\"');

            // EXCEPTION
            if (logEvent.Exception != null)
            {
                output.Write(",\"exception\":");
                JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), output);
            }

            // Serilog Message Template
            if (_includeMessageTemplate)
            {
                // Capitalized to match default Serilog JsonFormatter
                output.Write(",\"MessageTemplate\":");
                JsonValueFormatter.WriteQuotedJsonString(logEvent.MessageTemplate.Text, output);
            }

            // Custom Properties passed in by code logging
            foreach (var property in logEvent.Properties)
            {
                var name = property.Key;
                if (name.Length > 0 && name[0] == '@')
                {
                    // Escape first '@' by doubling
                    name = '@' + name;
                }

                WriteKeyValue(output, valueFormatter, name, property.Value);
            }

            output.Write('}');
            output.WriteLine();             // finish the log line

            // if we have blown the limit of a single stackdriver line (which means that error reporting won't parse
            // it correctly for instance) - then log that fact out too so we can adjust the logging and fix the problem
            if (_checkForPayloadLimit && (output.CharacterCount * 4) >= STACKDRIVER_ENTRY_LIMIT_BYTES)
            {
                string text            = "An attempt was made to write a log event to stackdriver that exceeds StackDriver Entry length limit - check logs for partially parsed entry just prior to this and fix at source";
                var    tooLongLogEvent = new LogEvent(
                    logEvent.Timestamp, LogEventLevel.Fatal, null,
                    new MessageTemplate(text, new MessageTemplateToken[] { new TextToken(text) }),                     // this is actually what gets rendered
                    new List <LogEventProperty>()
                    );
                FormatEvent(tooLongLogEvent, output, valueFormatter);
            }
        }