Reputation: 111
for the sake of having kind of the same setup in Java and C# (i know, terrible reason), I got this setup running in Java:
log4j:
<appender name="ELASTIC" class="ch.qos.logback.core.FileAppender">
...
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="FileBeatLayout" />
</encoder>
</appender>
Some information logging into MDC
MDC.Set("testIssue", testIssue.Replace("#", "-"));
MDC.Set("testType", testType);
MDC.Set("method", method.Name.ToLower());
MDC.Set("elapsedTime", elapsedTimeInNs.ToString());
MDC.Set("elapsedTimeUnit", "ns");
MDC.Set("platform", ".NET");
MDC.Set("platformVersion", Environment.Version.ToString());
MDC.Set("operatingSystem", $"{GetBaseOs()} {Environment.OSVersion.Version.Major}");
MDC.Set("jenkinsBuild", GetJenkinsBuildTagIfSet());
foreach (var version in testEnvironment.GetDependencyTreeDict())
{
MDC.Set(version.Key, version.Value);
}
_logger.Info("[{0}] *{1}* {2}: {3} ns", testIssue, testType, method.Name, elapsedTimeInNs);
log4net.ThreadContext.Properties["TIMING"] = "false";
MDC.Clear();
Finaly a custom Layout class writing the content of the MDC to the file as one json string per logging event. (Java)
public class FileBeatLayout extends LayoutBase<ILoggingEvent> {
@Override
public String doLayout(ILoggingEvent iLoggingEvent) {
StringBuilder stringBuilder = new StringBuilder();
Map<String, String> map = iLoggingEvent.getMDCPropertyMap();
JSONObject jsonObject = new JSONObject(map);
stringBuilder.append(jsonObject);
return stringBuilder.toString().replaceAll("[\\t \\n]", "") + "\n";
}
}
how do I do iterate over all values in MDC in C#, as in slf4net, this functionality is internal? I got this far (and this works insofar that it will write out that string for each event)
public class FileBeatLayout : LayoutSkeleton
{
public override void ActivateOptions()
{
}
public override void Format(TextWriter writer, LoggingEvent loggingEvent)
{
writer.WriteLine("The JSON object containing all MDC values");
}
}
Upvotes: 1
Views: 648
Reputation: 111
Found out myself after rubber ducking stackoverflow:
ThreadContext.Properties.GetKeys().ForEach(x => jsonObject.Add(x, ThreadContext.Properties[x]));
This seems to be the way to access whatever you write to MDC.
Upvotes: 1