string m = "message";
logger.Debug("A message: {Message}.", m);
output:
A message: "message".
You need to create a custom IValueFormatter for that and set
c#
ConfigurationItemFactory.Default.ValueFormatter
Another option is by not using structured logging:
logger.Debug("A message: {0}.", m);
You can also do use the :l format parameter (l = literal) to avoid the quotes:
```c#
string m = "message";
logger.Debug("A message: {Message:l}.", m);
But yes you can make it application wide by replacing `IValueFormatter` like this:
```c#
class OverrideValueFormatter : IValueFormatter
{
private IValueFormatter _originalFormatter;
public bool StringWithQuotes { get; set; }
public OverrideValueFormatter(IValueFormatter originalFormatter)
{
_originalFormatter = originalFormatter;
}
public bool FormatValue(object value, string format, NLog.MessageTemplates.CaptureType captureType, IFormatProvider formatProvider, System.Text.StringBuilder builder)
{
if (!StringWithQuotes && captureType == NLog.MessageTemplates.CaptureType.Normal)
{
switch (Convert.GetTypeCode(value))
{
case TypeCode.String:
{
builder.Append((string)value);
return true;
}
case TypeCode.Char:
{
builder.Append((char)value);
return true;
}
case TypeCode.Empty:
return true; // null becomes empty string
}
}
return _originalFormatter.FormatValue(value, format, captureType, formatProvider, builder);
}
}
And register it like this:
c#
var oldFormatter = NLog.Config.ConfigurationItemFactory.Default.ValueFormatter;
var newFormatter = new OverrideValueFormatter(oldFormatter);
newFormatter.StringWithQuotes = false;
NLog.Config.ConfigurationItemFactory.Default.ValueFormatter = newFormatter;
Thanks all. Great solutions. 馃尮
Most helpful comment
You can also do use the
:lformat parameter (l = literal) to avoid the quotes:```c#
string m = "message";
logger.Debug("A message: {Message:l}.", m);
And register it like this:
c# var oldFormatter = NLog.Config.ConfigurationItemFactory.Default.ValueFormatter; var newFormatter = new OverrideValueFormatter(oldFormatter); newFormatter.StringWithQuotes = false; NLog.Config.ConfigurationItemFactory.Default.ValueFormatter = newFormatter;