private 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.UtcDateTime.ToString("O")); output.Write("\",\"Level\":\""); output.Write(logEvent.Level); output.Write("\",\"Message\":"); 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.Properties, output); } output.Write('}'); }
/// <inheritdoc cref="ColumnWriterBase" /> /// <summary> /// Gets the part of the log event to write to the column. /// </summary> /// <param name="logEvent">The log event.</param> /// <param name="formatProvider">The format provider.</param> /// <returns> /// An object value. /// </returns> /// <seealso cref="ColumnWriterBase" /> public override object GetValue(LogEvent logEvent, IFormatProvider formatProvider = null) { if (!logEvent.Properties.ContainsKey(this.Name)) { return(DBNull.Value); } // ReSharper disable once SwitchStatementMissingSomeCases switch (this.WriteMethod) { case PropertyWriteMethod.Raw: return(GetPropertyValue(logEvent.Properties[this.Name])); case PropertyWriteMethod.Json: var valuesFormatter = new JsonValueFormatter(); var sb = new StringBuilder(); using (var writer = new StringWriter(sb)) { valuesFormatter.Format(logEvent.Properties[this.Name], writer); } return(sb.ToString()); default: return(logEvent.Properties[this.Name].ToString(this.Format, formatProvider)); } }
private object GetProperty(IReadOnlyDictionary <string, LogEventPropertyValue> properties, string name) { LogEventPropertyValue value; if (!properties.TryGetValue(name, out value)) { return(null); } var scalar = value as ScalarValue; if (scalar != null) { return(scalar.Value); } else { using (var result = new StringWriter()) { var formater = new JsonValueFormatter(); formater.Format(value, result); return(result.ToString()); } } }
private static void WritePropertyAndValue(TextWriter output, string propertyKey, string propertyValue) { JsonValueFormatter.WriteQuotedJsonString(propertyKey, output); output.Write(":"); JsonValueFormatter.WriteQuotedJsonString(propertyValue, output); output.Write(","); }
/// <summary> /// Construct a <see cref="JsonValueFormatter"/>, optionally supplying a formatter for /// <see cref="LogEventPropertyValue"/>s on the event. /// </summary> /// <param name="appName">Name of the application.</param> /// <param name="appVersion">Version of the application.</param> /// <param name="renderMessageTemplate">Whether or not the message template should be rendered.</param> /// <param name="valueFormatter">A value formatter, or null.</param> public CustomSerilogFormatter(string appName, string appVersion, bool renderMessageTemplate = false, JsonValueFormatter valueFormatter = null) { _appName = appName; _appVersion = appVersion; _renderMessageTemplate = renderMessageTemplate; _valueFormatter = valueFormatter ?? new JsonValueFormatter(typeTagName: "$type"); }
static void WriteRenderings(IEnumerable <IGrouping <string, PropertyToken> > tokensWithFormat, IReadOnlyDictionary <string, LogEventPropertyValue> properties, TextWriter output) { output.Write("\"Renderings\":{"); string precedingDelimiter = ""; foreach (var ptoken in tokensWithFormat) { output.Write(precedingDelimiter); precedingDelimiter = COMMA_DELIMITER; JsonValueFormatter.WriteQuotedJsonString(ptoken.Key, output); output.Write(":["); var fdelim = ""; foreach (var format in ptoken) { output.Write(fdelim); fdelim = COMMA_DELIMITER; 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 string ToJson(IReadOnlyDictionary <string, LogEventPropertyValue> properties) { if (properties.Count < 1) { return(""); } var formater = new JsonValueFormatter(); using (var result = new StringWriter()) { result.Write('{'); var i = 0; foreach (KeyValuePair <string, LogEventPropertyValue> property in properties) { if (i > 0) { result.Write(','); } result.Write('\n'); JsonValueFormatter.WriteQuotedJsonString(property.Key, result); result.Write(": "); formater.Format(property.Value, result); ++i; } result.Write("\n}"); return(result.ToString()); } }
static string DefaultFormatter(IReadOnlyDictionary <string, LogEventPropertyValue> properties) { var valueFormatter = new JsonValueFormatter(null); var propertiesBuilder = new StringBuilder(); using (var writer = new StringWriter(propertiesBuilder)) { var delimiter = ""; writer.Write("{"); foreach (var property in properties) { writer.WriteLine(delimiter); delimiter = ","; JsonValueFormatter.WriteQuotedJsonString(property.Key, writer); writer.Write(":"); valueFormatter.Format(property.Value, writer); } writer.WriteLine(); writer.Write("}"); } return(propertiesBuilder.ToString()); }
private object PropertiesToJson(LogEvent logEvent) { if (logEvent.Properties.Count == 0) { return("{}"); } var valuesFormatter = new JsonValueFormatter(); var sb = new StringBuilder(); sb.Append("{"); using (var writer = new System.IO.StringWriter(sb)) { foreach (var logEventProperty in logEvent.Properties) { sb.Append($"\"{logEventProperty.Key}\":"); valuesFormatter.Format(logEventProperty.Value, writer); sb.Append(", "); } } sb.Remove(sb.Length - 2, 2); sb.Append("}"); return(sb.ToString()); }
public static void WriteRenderings(this TextWriter writer, LogEvent logEvent) { 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()) { writer.Write(",\"@r\":["); var delim = ""; // ReSharper disable once PossibleMultipleEnumeration foreach (var r in tokensWithFormat) { writer.Write(delim); delim = ","; var space = new StringWriter(); r.Render(logEvent.Properties, space); JsonValueFormatter.WriteQuotedJsonString(space.ToString(), writer); } writer.Write(']'); } }
/// <summary> /// Construct a <see cref="SplunkJsonFormatter"/>. /// </summary> /// <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> /// <param name="index">The Splunk index to log to</param> /// <param name="debugLevel">If true, exception details will be logged.</param> public SplunkJsonFormatter(bool debugLevel, string source = null, string sourceType = null, string host = null, string index = null) { _debugLevel = debugLevel; 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(); }
/// <param name="index">The Splunk index to log to</param> /// <param name="source">The source of the event</param> public JsonEventFormatter( EventSource source, string index ) { this.source = source; var suffixWriter = new StringWriter(); suffixWriter.Write("}"); // Terminates "event" if (!string.IsNullOrWhiteSpace(source.ApplicationName)) { suffixWriter.Write(",\"source\":"); JsonValueFormatter.WriteQuotedJsonString(source.ApplicationName, suffixWriter); suffixWriter.Write(",\"sourcetype\":"); JsonValueFormatter.WriteQuotedJsonString("httpevent", suffixWriter); } if (!string.IsNullOrWhiteSpace(source.Host)) { suffixWriter.Write(",\"host\":"); JsonValueFormatter.WriteQuotedJsonString(source.Host, suffixWriter); } if (!string.IsNullOrWhiteSpace(index)) { suffixWriter.Write(",\"index\":"); JsonValueFormatter.WriteQuotedJsonString(index, suffixWriter); } suffixWriter.Write('}'); // Terminates the payload suffix = suffixWriter.ToString(); }
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($"{{\"time\":\"{logEvent.Timestamp:O}\","); output.Write("\"data\":{"); output.Write($"\"level\":\"{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.Any()) { WriteProperties(logEvent.Properties, output); } output.Write('}'); output.Write('}'); }
static void WriteProperties( IEnumerable <KeyValuePair <string, LogEventPropertyValue> > properties, TextWriter output ) { output.Write(",\"Data\":{"); var precedingDelimiter = ""; foreach (var property in properties.Where(IsRenderedProperty)) { StructureValue structure = property.Value as StructureValue; if (structure != null) { FlattenAndWriteStructure(structure, output, ref precedingDelimiter); } else { output.Write(precedingDelimiter); precedingDelimiter = ","; JsonValueFormatter.WriteQuotedJsonString(property.Key, output); output.Write(':'); ValueFormatter.Format(property.Value, output); } } output.Write('}'); }
private string ResolveDetailsFromLogEvent(LogEvent logEvent) { if ((logEvent.Properties == null) || (logEvent.Properties.Count == 0)) { return(null); } //otherwise lets serialize these to JSON... var valueFormatter = new JsonValueFormatter(); var output = new StringWriter(); output.Write("{\r\n"); foreach (var property in logEvent.Properties) { var name = property.Key; if (name.Length > 0 && name[0] == '@') { // Escape first '@' by doubling name = '@' + name; } output.Write("\t"); JsonValueFormatter.WriteQuotedJsonString(name, output); output.Write(" : "); valueFormatter.Format(property.Value, output); output.Write(",\r\n"); } output.Write("}\r\n"); return(output.ToString()); }
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('{'); 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> /// Construct a <see cref="RedisCompactJsonFormatter"/>, optionally supplying a formatter for /// <see cref="LogEventPropertyValue"/>s on the event. /// </summary> /// <param name="config">Formatter configuration</param> /// <param name="redisConfig">Redis configuration</param> /// <param name="valueFormatter">A value formatter, or null.</param> public RedisCompactJsonFormatter(IFormatterConfiguration config, RedisConfiguration redisConfig, JsonValueFormatter valueFormatter = null) { _config = config; _redisConfig = redisConfig; _valueFormatter = valueFormatter ?? new JsonValueFormatter(typeTagName: "$type"); }
/** * Taken from: * https://github.com/serilog/serilog-formatting-compact/blob/dev/src/Serilog.Formatting.Compact/Formatting/Compact/CompactJsonFormatter.cs */ private string Property2JSON(IReadOnlyDictionary <string, LogEventPropertyValue> properties) { var output = new StringWriter(); var valueFormatter = new JsonValueFormatter(typeTagName: "$type"); var first = true; output.Write('{'); foreach (var property in properties) { var name = property.Key; if (name == LoggerFactory.LoggerNamePropertyName) { continue; } if (name.Length > 0 && name[0] == '@') { // Escape first '@' by doubling name = '@' + name; } if (!first) { output.Write(','); } JsonValueFormatter.WriteQuotedJsonString(name, output); output.Write(':'); valueFormatter.Format(property.Value, output); first = false; } output.Write('}'); return(output.ToString()); }
private void DefaultSuffixPropertiesSplunk(LogSplunkMapper mapper) { var suffixWriter = new StringWriter(); suffixWriter.Write("}"); // Terminates "event" if (!string.IsNullOrWhiteSpace(mapper.Source)) { suffixWriter.Write(",\"source\":"); JsonValueFormatter.WriteQuotedJsonString(mapper.Source, suffixWriter); } if (!string.IsNullOrWhiteSpace(mapper.SourceType)) { suffixWriter.Write(",\"sourcetype\":"); JsonValueFormatter.WriteQuotedJsonString(mapper.SourceType, suffixWriter); } if (!string.IsNullOrWhiteSpace(mapper.Host)) { suffixWriter.Write(",\"host\":"); JsonValueFormatter.WriteQuotedJsonString(mapper.Host, suffixWriter); } if (!string.IsNullOrWhiteSpace(mapper.Index)) { suffixWriter.Write(",\"index\":"); JsonValueFormatter.WriteQuotedJsonString(mapper.Index, suffixWriter); } suffixWriter.Write('}'); // Terminates the types of Splunk _suffix = suffixWriter.ToString(); }
public override object GetValue(LogEvent logEvent, IFormatProvider formatProvider = null) { if (!logEvent.Properties.ContainsKey(Name)) { return(DBNull.Value); } switch (WriteMethod) { case PropertyWriteMethod.Raw: return(GetPropertyValue(logEvent.Properties[Name])); case PropertyWriteMethod.Json: var valuesFormatter = new JsonValueFormatter(); var sb = new StringBuilder(); using (var writer = new System.IO.StringWriter(sb)) { valuesFormatter.Format(logEvent.Properties[Name], writer); } return(sb.ToString()); default: return(logEvent.Properties[Name].ToString(Format, formatProvider)); } }
private void WriteTokensWithFormat( IReadOnlyDictionary <string, LogEventPropertyValue> properties, IEnumerable <MessageTemplateToken> tokens, StringWriter writer) { var tokensWithFormat = tokens .OfType <PropertyToken>() .Where(pt => pt.Format != null); if (tokensWithFormat.Any()) { writer.Write(",\"@r\":["); var delim = ""; foreach (var r in tokensWithFormat) { writer.Write(delim); delim = ","; using (var space = new StringWriter()) { r.Render(properties, space); JsonValueFormatter.WriteQuotedJsonString(space.ToString(), writer); } } writer.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\":{\"Severity\":\""); output.Write(logEvent.Level); output.Write('"'); // Configure common event source properties LogEventPropertyValue eventName = null; foreach (var eventSourcePropertyName in EventSourceProperties) { if (logEvent.Properties.TryGetValue(eventSourcePropertyName, out eventName)) { if (eventSourcePropertyName == "SourceContext") { output.Write($",\"LoggerName\":"); } else { output.Write($",\"{eventSourcePropertyName}\":"); } ValueFormatter.Format(eventName, output); } } if (logEvent.Exception != null) { output.Write(",\"Exception\":"); JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), output); } var propertiesToRender = logEvent.Properties.Where(IsRenderedProperty); if (propertiesToRender.Count() != 0) { WriteProperties(propertiesToRender, output); } var message = logEvent.RenderMessage(null); if (!(string.IsNullOrWhiteSpace(message) || message == EventLogger.EventDataTemplate)) { output.Write(",\"Message\":"); JsonValueFormatter.WriteQuotedJsonString(message, output); } output.WriteLine(suffix); }
/// <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(nameof(logEvent)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } output.Write("{\"Message\":"); JsonValueFormatter.WriteQuotedJsonString(logEvent.MessageTemplate.Render(logEvent.Properties), output); output.Write(",\"MessageTemplate\":"); JsonValueFormatter.WriteQuotedJsonString(logEvent.MessageTemplate.Text, 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 if (tokensWithFormat.Any()) { output.Write(",\"Renderings\":["); var delimiter = string.Empty; foreach (var r in tokensWithFormat) { output.Write(delimiter); delimiter = ","; var space = new StringWriter(); r.Render(logEvent.Properties, space); JsonValueFormatter.WriteQuotedJsonString(space.ToString(), output); } output.Write(']'); } if (logEvent.Exception != null) { output.Write(",\"Exception\":"); SerializeException( output, logEvent.Exception, 1); } foreach (var(key, value) in logEvent.Properties) { var name = GetSanitizedPropertyName(key); output.Write(','); JsonValueFormatter.WriteQuotedJsonString(name, output); output.Write(':'); _valueFormatter.Format(value, output); } output.Write('}'); }
public StackdriverJsonFormatter(bool checkForPayloadLimit = true, bool includeMessageTemplate = true, JsonValueFormatter valueFormatter = null) { _checkForPayloadLimit = checkForPayloadLimit; _includeMessageTemplate = includeMessageTemplate; _valueFormatter = valueFormatter ?? new JsonValueFormatter(typeTagName: "$type"); }
private static void AppendMessage(LogEvent logEvent, TextWriter output) { output.Write("{\"Message\":"); var message = logEvent.MessageTemplate.Render(logEvent.Properties); JsonValueFormatter.WriteQuotedJsonString(message, output); }
private static void WriteException(Exception exception, StringWriter writer) { if (exception != null) { writer.Write(",\"@x\":"); JsonValueFormatter.WriteQuotedJsonString(exception.ToString(), writer); } }
static string Format(TemplatePropertyValue value) { var formatter = new JsonValueFormatter(); var output = new StringWriter(); formatter.Format(value, output); return(output.ToString()); }
public void FormatPropertiesSplunk(LogEvent logEvent, TextWriter output, LogSplunkMapper logData) { if (logEvent == null) { throw new ArgumentNullException(nameof(logEvent)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } output.Write("{\"time\":\""); output.Write(logData.Time); output.Write("\",\"event\":{"); if (!string.IsNullOrWhiteSpace(logData.Event.Message)) { output.Write("\"Message\":"); JsonValueFormatter.WriteQuotedJsonString(logData.Event.Message, output); } if (!string.IsNullOrWhiteSpace(logData.Event.ProcessName)) { output.Write(",\"ProcessName\":"); JsonValueFormatter.WriteQuotedJsonString(logData.Event.ProcessName, output); } if (!string.IsNullOrWhiteSpace(logData.Event.ProductCompany)) { output.Write(",\"ProductCompany\":"); JsonValueFormatter.WriteQuotedJsonString(logData.Event.ProductCompany, output); } if (!string.IsNullOrWhiteSpace(logData.Event.ProductName)) { output.Write(",\"ProductName\":"); JsonValueFormatter.WriteQuotedJsonString(logData.Event.ProductName, output); } if (!string.IsNullOrWhiteSpace(logData.Event.ProductVersion)) { output.Write(",\"ProductVersion\":"); JsonValueFormatter.WriteQuotedJsonString(logData.Event.ProductVersion, output); } if (!string.IsNullOrWhiteSpace(logData.Event.Severity)) { output.Write(",\"Severity\":"); JsonValueFormatter.WriteQuotedJsonString(logData.Event.Severity, output); } string[] aditionalDataToBeRemoved = { "SplunkIndex", "ProductCompany", "ProductVersion", "ProcessName" }; var propertiesFiltered = logEvent.Properties.Where(p => !aditionalDataToBeRemoved.Contains(p.Key)).ToDictionary(d => d.Key, d => d.Value); WriteProperties(propertiesFiltered, output, logEvent.Exception); output.WriteLine(_suffix); }
/// <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)); } output.Write("{\"timestamp\":"); output.Write((long)logEvent.Timestamp.UtcDateTime.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds); output.Write(",\"template\":"); JsonValueFormatter.WriteQuotedJsonString(logEvent.MessageTemplate.Text, output); output.Write(",\"message\":"); JsonValueFormatter.WriteQuotedJsonString(logEvent.MessageTemplate.Render(logEvent.Properties), output); var tokensWithFormat = logEvent.MessageTemplate.Tokens .OfType <PropertyToken>() .Where(pt => pt.Format != null); if (logEvent.Level != LogEventLevel.Information) { output.Write(",\"level\":\""); output.Write(logEvent.Level); output.Write('\"'); } if (logEvent.Exception != null) { output.Write(",\"exception\":"); JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), output); } if (logEvent.Properties.Count != 0) { output.Write(",\"properties\":{"); var precedingDelimiter = ""; foreach (var property in logEvent.Properties) { output.Write(precedingDelimiter); precedingDelimiter = ","; JsonValueFormatter.WriteQuotedJsonString(property.Key, output); output.Write(':'); valueFormatter.Format(property.Value, output); } output.Write('}'); } output.Write('}'); }
public LogFormatter(JsonValueFormatter valueFormatter = null) { _serializer = new JsonSerializer { NullValueHandling = NullValueHandling.Ignore, }; _serializer.Converters.Add(new LogEventPropertyValueConverter()); }
static string Format(LogEventPropertyValue value) { var formatter = new JsonValueFormatter(); var output = new StringWriter(); formatter.Format(value, output); return output.ToString(); }
public void WhenNullNoTypeTagIsWritten() { var structure = new StructureValue(new LogEventProperty[0], "T"); var formatter = new JsonValueFormatter(null); var output = new StringWriter(); formatter.Format(structure, output); var f = output.ToString(); Assert.Equal("{}", f); }
public void TypeTagCanBeOverridden() { var structure = new StructureValue(new LogEventProperty[0], "T"); var formatter = new JsonValueFormatter("$type"); var output = new StringWriter(); formatter.Format(structure, output); var f = output.ToString(); Assert.Equal("{\"$type\":\"T\"}", f); }