【问题标题】:Writing file as JSON using NLog in a programmatic way以编程方式使用 NLog 将文件写入 JSON
【发布时间】:2017-09-22 15:45:30
【问题描述】:

我想使用 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。任何帮助或提示将不胜感激

【问题讨论】:

    标签: c# json logging nlog


    【解决方案1】:

    看起来您可能缺少布局。这行得通

    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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 2023-03-11
      • 2016-12-14
      相关资源
      最近更新 更多