I have the following IValueFormatter :
public class NLogValueFormatter : IValueFormatter{ public bool FormatValue(object value, string format, CaptureType captureType, IFormatProvider formatProvider, StringBuilder builder) { if (value.GetType() == typeof(LogData)) return false; builder.Append(format); try { var myTarget = LogManager.Configuration.FindTargetByName("communicationFileLog"); myTarget = ((myTarget as NLog.Targets.Wrappers.WrapperTargetBase)?.WrappedTarget) ?? myTarget; var jsonLayout = (myTarget as NLog.Targets.TargetWithLayout)?.Layout as NLog.Layouts.JsonLayout; if (jsonLayout?.MaxRecursionLimit > 0) { var jsonSettings = new JsonSerializerSettings() { MaxDepth = jsonLayout?.MaxRecursionLimit }; using (var stringWriter = new StringWriter()) { try { using (var jsonWriter = new JsonTextWriterMaxDepth(stringWriter, jsonSettings)) JsonSerializer.Create(jsonSettings).Serialize(jsonWriter, value); } catch (Exception) { } builder.Append(stringWriter.ToString()); } } else value = null; } catch (Exception ex) { builder.Append($"Failed to serlize {value.GetType()} : {ex.ToString()}"); } return true; }}
The goal with this is to do a JSON serializationthat I can set depth on.
This line of code is executed at statup :
NLog.Config.ConfigurationItemFactory.Default.ValueFormatter = new NLogValueFormatter();
To log data I got this code :
public void LogCommunication(CallInformation callInfo) { _comLogger.Log(LogLevel.Info, "ComLogger : {@callInfo}", callInfo); }
In Nlog.config I got this :
<logger name="CommunicationLogger" minlevel="Trace" writeto="communicationFileLog"></logger><target xsi:type="File" name="communicationFileLog" fileName="${basedir}/logs/${shortdate}.log" maxArchiveDays="5" maxArchiveFiles="10"><layout xsi:type="JsonLayout" includeAllProperties="true" maxRecursionLimit="1"></layout></target>
I can see that the FormatValue is executed but the builder contents seems to never end up in the logfile. I do however get some kind of standard serialization in the file but I dont know where it comes from, meybe the includeAllProperties=true. It is not respecting the maxRecursionLimit anyway.
How do I get the IValurFormatter to put out text to the file instead of the standard one?
Regards