【问题标题】:Logging with NLog into an Isolated Storage使用 NLog 记录到隔离存储中
【发布时间】:2010-10-26 15:55:51
【问题描述】:

我在我的 C# Win Forms 中使用 NLog 库 (http://nlog-project.org/) 来进行日志记录。 如果可以使用此 NLogger 将日志文件写入“隔离存储”,有没有人有经验?

谢谢 4 个答案

【问题讨论】:

    标签: .net winforms isolatedstorage nlog


    【解决方案1】:

    我没有在 Silverlight 中使用过 NLog,但是一个新版本 2.0 刚刚发布到测试版中,它可以在 Silverlight 中使用(网站上有一些示例)。我还没有见过一个独立的存储目标,但我敢打赌,写一个并不难。

    This link shows(在 Christian 的回答中)一种“记录”到隔离存储的方法。我无法评论这是否是一个好主意。有了这些信息,您可能可以编写一个 NLog Target,该目标可以配置到 NLog 中,以便 NLog 记录器可以写入隔离存储。

    Here is another example(在 Chris S 的回答中)记录到隔离存储。

    最后,NLog 2.0 确实带有我认为可从 Silverlight 客户端使用的 LogReceiveService 和 LogReceiverServiceTarget。我还没有这样做,所以我无法评论它们是否有效或如何工作。

    按照克里斯蒂安的例子,你可以做这样的事情(我没试过):

    [Target("IsolatedStorage")]
    public sealed class IsolatedStorageTarget : TargetWithLayout    
    {        
      public IsolatedStorageTarget()
      {            
      }
      protected override void Write(LogEventInfo logEvent)        
      {
        try 
        { 
          using (IsolatedStorageFile store = 
                 IsolatedStorageFile.GetUserStoreForApplication()) 
          { 
            using (Stream stream = new IsolatedStorageFileStream
                   ("Solution.Silverlight.log", FileMode.Append, FileAccess.Write, store)) 
            { 
              StreamWriter writer = new StreamWriter(stream); 
              writer.WriteLine(this.Layout.Render(logEvent));
            } 
            writer.Close(); 
          } 
        } 
        catch (Exception ex) 
        { 
        } 
      }
    }
    

    我能想到的可能会改善这一点的一些事情是:

    也许只要目标还活着,就最好保持流和文件打开。可能可以通过覆盖 InitializeTarget 和 CloseTarget 来做到这一点。

    也许允许指定文件名而不是使用硬编码的文件名会更好。

    一些错误处理可能有用。至少检测隔离存储是否已用尽,并且可能正常(或静默)失败。

    如果你走这条路,祝你好运!报告您是否成功。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      相关资源
      最近更新 更多