2013-03-10 141 views
1

我堅持NLog日誌語句我的RavenDb數據庫。代表日誌語句的LogEventInfo類具有一個屬性LogLevel,它帶有一個私有構造函數。 LogLevel(Info,Warn等)的實例通過調用私有構造函數的靜態只讀屬性創建。JsonSerializationException類型與私有構造函數

的問題是,我想讀消息從數據庫中查詢,併爲他們拋出一個Json.Net序列化錯誤:

Unable to find a constructor to use for type NLog.LogLevel. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'Level.Name'.

我怎樣才能解決這個錯誤嗎?可以在這裏創建某種Raven索引嗎?

+0

您可以編寫自定義'JsonConverter'如果你喜歡,或者你可以像Xha一樣做rze說,並使用自己的類來記錄日誌數據,而不是直接存儲NLog類。 – 2013-03-11 04:38:30

+0

我傾向於一個自定義類。鑑於'LogLevel'的設計方式,在反序列化過程中我不得不忽略它,因爲它是記錄信息的關鍵部分,所以我不想這樣做。 – levelnis 2013-03-11 07:54:43

回答

1

我認爲最簡單的方法是創建一個自定義類來保存所有的日誌信息。

1

它曾與我這個樣子

create a CustomCreationConverter,並與你的對象的反序列化使用

public class EventInfoConverter : CustomCreationConverter<LogEventInfo> 
    { 
     private string _level { get; set; } 
     public EventInfoConverter(string s) 
     { 
      JToken eventinfo = JObject.Parse(s); 
      var childs = eventinfo.Children(); 
      foreach (var item in childs) 
      { 
       if (((Newtonsoft.Json.Linq.JProperty)item).Name == "Level") 
       { 
        var m = ((Newtonsoft.Json.Linq.JProperty)item).Value.Children(); 
        foreach (var item1 in m) 
        { 
         _level = ((Newtonsoft.Json.Linq.JProperty)item1).Value.ToString(); 
         break; 
        } 

        break; 
       } 
      } 
     } 

     public override LogEventInfo Create(Type objectType) 
     { 
      LogEventInfo eventInfo = new LogEventInfo(); 
      switch (_level) 
      { 
       case "Info": 
         eventInfo = new LogEventInfo(LogLevel.Info, "", ""); 
        break; 
       case "Debug": 
        eventInfo = new LogEventInfo(LogLevel.Debug, "", ""); 
        break; 
       case "Error": 
        eventInfo = new LogEventInfo(LogLevel.Error, "", ""); 
        break; 
       case "Warn": 
        eventInfo = new LogEventInfo(LogLevel.Warn, "", ""); 
        break; 
       default: 
        break; 
      } 
      return eventInfo; 
     } 
    } 
  • 在你反序列化:

    NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger(); 
    _logger.Log(Newtonsoft.Json.JsonConvert.DeserializeObject<LogEventInfo>(eventInfo, new EventInfoConverter(eventInfo))); 
    
+0

儘管這個鏈接可能回答這個問題,但最好在這裏包含答案的基本部分,並提供供參考的鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 - [來自評論](/ review/low-quality-posts/18218729) – yivi 2017-12-11 13:04:30

+0

謝謝yivi,注意! – 2017-12-11 16:29:04

相關問題