问题
I use the NLog Libary (http://nlog-project.org/) within my C# Win Forms to do the logging. Has anyone some experiance if it's possible to write the Logfile into an "IsolatedStorage" with this NLogger?
Thx 4 answers
回答1:
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.
来源:https://stackoverflow.com/questions/4025471/logging-with-nlog-into-an-isolated-storage