Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add LogEvent properties as additional fields in the GELF message #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions NLog.Target.Gelf/GelfMessage.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.Generic;
using Newtonsoft.Json;

namespace NLog.Targets.Gelf
Expand Down Expand Up @@ -34,5 +35,8 @@ internal class GelfMessage

[JsonProperty("_notes")]
public string Notes { get; set; }

[JsonExtensionData]
public Dictionary<string, object> Properties { get; set; }
}
}
3 changes: 2 additions & 1 deletion NLog.Target.Gelf/NLog.Targets.Gelf.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,8 @@ private string CreateGelfJsonFromLoggingEvent(LogEventInfo logEventInfo)
Host = Dns.GetHostName(),
Level = logEventInfo.Level.GelfSeverity(),
ShortMessage = shortMessage,
Logger = logEventInfo.LoggerName ?? ""
Logger = logEventInfo.LoggerName ?? "",
Properties = logEventInfo.Properties.ToDictionary(x => "_" + x.Key, y => y.Value)
};

if (logEventInfo.Properties != null)
Expand Down
25 changes: 19 additions & 6 deletions TestApp/Form1.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions TestApp/Form1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ private void ButtonLog_Click(object sender, EventArgs e)
case "buttonFatal":
Logger.Fatal("This is a sample fatal message");
break;
case "buttonCustomFields":
LogEventWithCustomProperties(LogLevel.Trace, "This is a message with custom fields");
break;
case "buttonRandomMessage":
// 32 is a space, the rest are the upper case alphabet.
var byteValues = new[] {32, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90};
Expand All @@ -65,5 +68,13 @@ private void ButtonLog_Click(object sender, EventArgs e)
break;
}
}

private static void LogEventWithCustomProperties(LogLevel level, string message)
{
var theEvent = new LogEventInfo(level, "logger-name", message);
theEvent.Properties["MyCustomValue"] = "custom";
theEvent.Properties["AnotherCustomValue"] = "custom2";
Logger.Log(theEvent);
}
}
}