Search code examples
c#nlogstring-interpolation

Extra quotes when logging objects with NLog


I have a code that outputs interpolated string to the log with NLog.

Here is an example

_logger.LogDebug($"REQUEST {webRequest.RequestUri}", Id)
WebResponse webResponse = await _httpService.SendRequestAsync(webRequest);
var response = ParseResponse(webResponse);
_logger.LogDebug($"RESPONSE {(int)response.StatusCode} {JsonConvert.SerializeObject(response.Body)}", Id);

In this example, in a first case of calling the function _logger.LogDebug, I get the expected result as a result:

2019-04-15 09:27:24.5027 DEBUG e1701b07-d228-4543-a320-3cb1b7f2e4b0 REQUEST http://url/

But in the second case, the expected result is wrapped in additional quotes.

2019-04-15 09:27:57.2907 DEBUG "e1701b07-d228-4543-a320-3cb1b7f2e4b0 RESPONSE 200 [{...},{...}]"

Here is the _logger.LogDebug method

using NLog;

private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

public void LogDebug(string message, Guid id)
{
    Logger.Debug($"{id.ToString()} {message}");
}

The result of the JsonConvert.SerializeObject(response.Body) is a string representation of array of json eg: [{"key":"value","key":"value"},{"key":"value","key":"value"}]

Here is a part of my Nlog.config

  <targets>

    <target name="csv" xsi:type="File" fileName="${shortdate}-${level}-services.log">
      <layout xsi:type="CSVLayout" delimiter="Tab" withHeader="false">
        <column name="time" layout="${longdate}" />
        <column name="level" layout="${uppercase:${level}}"/>
        <column name="message" layout="${message}" />
      </layout>
    </target>

  </targets>

  <rules>
    <logger name="*" minlevel="Debug" writeTo="csv" />
  </rules>

Why do I get additional quotes in the second case and how can I avoid it?


Solution

  • As per the docs,

    CSV Options quoting - Default Quoting mode for columns.

    Default: Auto

    Possible values:

    Auto - Quote only whose values contain the quote symbol, the separator or newlines (Slow)

    All - Quote all column. Useful for data known to be multiline such as Exception-ToString

    (Fast) Nothing - Quote nothing (Very Fast)

    The default is Auto - which means it is quoting your string since it contains a quote, a tab (the separator) or a new line.

    It is important it does this, so that the file is a valid CSV file (otherwise Excel etc don't know where the column data begins and ends.