Skip to content

Instantly share code, notes, and snippets.

@pavel-khritonenko
Created May 24, 2019 12:20
Show Gist options
  • Save pavel-khritonenko/b97262e162b11e85653a09674b93d441 to your computer and use it in GitHub Desktop.
Save pavel-khritonenko/b97262e162b11e85653a09674b93d441 to your computer and use it in GitHub Desktop.
public sealed class GelfJsonFormatter : ITextFormatter
{
private static readonly IReadOnlyDictionary<LogEventLevel, short> Levels
= new Dictionary<LogEventLevel, short>()
{
{ LogEventLevel.Verbose, 7 },
{ LogEventLevel.Debug, 6 },
{ LogEventLevel.Information, 5 },
{ LogEventLevel.Warning, 4 },
{ LogEventLevel.Error, 3 },
{ LogEventLevel.Fatal, 0 },
};
public void Format(LogEvent logEvent, TextWriter output)
{
using (var json = new JsonTextWriter(output)
{
CloseOutput = false,
Formatting = Formatting.None
})
{
json.WriteStartObject();
json.WritePropertyName("version");
json.WriteValue("1.1");
json.WritePropertyName("host");
json.WriteValue(Environment.MachineName);
json.WritePropertyName("short_message");
json.WriteValue(logEvent.RenderMessage());
json.WritePropertyName("timestamp");
json.WriteValue(logEvent.Timestamp.ToUnixTimeSeconds());
json.WritePropertyName("level");
json.WriteValue(Levels[logEvent.Level]);
if (logEvent.Exception != null)
{
json.WritePropertyName("_error");
json.WriteValue(logEvent.Exception.Message);
json.WritePropertyName("_error_details");
json.WriteValue(logEvent.Exception.ToString());
}
foreach (var (key, value) in logEvent.Properties)
{
json.WritePropertyName($"_{key}");
json.WriteValue(value.ToString());
}
json.WriteEndObject();
}
output.WriteLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment