使用NLog以编程方式将文件写为JSON

时间:2017-09-22 15:45:31

标签: c# json logging nlog

我想使用NLog将文件写为JSON。我知道可以这样做。

<target name="jsonFile" xsi:type="File" fileName="${logFileNamePrefix}.json">
    <layout xsi:type="JsonLayout">
       <attribute name="time" layout="${longdate}" />
       <attribute name="level" layout="${level:upperCase=true}"/>
       <attribute name="message" layout="${message}" />
    </layout>
</target>

但我想用我的C#代码来做。我从这开始:

  var config = new LoggingConfiguration();

  var fileTarget = new FileTarget();
  string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);

  string fullPath = Path.Combine(folder, "mylog.json");
  fileTarget.FileName = fullPath;

  config.AddTarget("file", fileTarget);        
  var fileRule = new LoggingRule("*", LogLevel.Error, fileTarget);
  config.LoggingRules.Add(fileRule);           

  LogManager.Configuration = config;

但它只将其写为文件而不是JSON。任何帮助或提示将不胜感激

1 个答案:

答案 0 :(得分:2)

看起来您可能错过了布局。这工作

var fileTarget = new FileTarget()
{
    Name = "JSonTarget",
    FileName = @"C:\Temp\Json.txt"
};

var JSLayout = new JsonLayout();
JSLayout.Attributes.Add(new JsonAttribute("time", "${longdate}"));
JSLayout.Attributes.Add(new JsonAttribute("level", "${level:upperCase=true}"));
JSLayout.Attributes.Add(new JsonAttribute("message", "${message}"));

fileTarget.Layout = JSLayout;

var JSonTargetRule = new LoggingRule("*", LogLevel.Trace, fileTarget);

LogManager.Configuration.AddTarget("JSonTarget", fileTarget);
LogManager.Configuration.LoggingRules.Add(JSonTargetRule);

LogManager.ReconfigExistingLoggers();

var _logger = LogManager.GetCurrentClassLogger();

_logger.Info("JSON Informational Message");
_logger.Debug("JSON Debug Message");