Logging with NLog into an Isolated Storage

。_饼干妹妹 提交于 2019-12-01 09:09:18
wageoghe

I have not used NLog in Silverlight, but a new version, 2.0, has just been released into beta and it is usable in Silverlight (there are some examples on the website). I have not seen an Isolated Storage Target, but I bet it would not be difficult to write one.

This link shows (in Christian's answer) one way to "log" to isolated storage. I can't comment on whether or not it is a good idea. With that information, you could probably write a NLog Target that could be configured into NLog so that NLog loggers could write to isolated storage.

Here is another example (in the answer by Chris S) of logging to isolated storage.

Finally, NLog 2.0 does come with a LogReceiveService and a LogReceiverServiceTarget that I think are usable from a Silverlight client. I have not done so, so I cannot comment on if they work or how they work.

Going by Christian's example, you could do something like this (I have not tried this):

[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) 
    { 
    } 
  }
}

Some things I can think of that might improve this are:

Maybe it is better to keep the stream and the file open as long as the Target is alive. Could probably do this by overriding InitializeTarget and CloseTarget.

Maybe it would be nice to allow the filename to be specified rather than using hardcoded filename.

Some error handling might be useful. At least detecting if the isolated storage has been exhausted and maybe failing gracefully (or silently).

If you go this route, Good Luck! Report back on whether you are successful or not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!