What would be the best way to constantly write to a logfile without using the internal logging system (LoggingSession)? I did something like:
function raisedWhenNewLogMessageArrived(message) {
var fileName = getcurrentDate() + ".log";
var appDataDir = WinJS.Application.local.folder;
appDataDir.getFolderAsync("log", Windows.Storage.CreationCollisionOption.openIfExists).then(
function (folder) {
folder.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.openIfExists).then(
function (file) {
Windows.Storage.FileIO.appendTextAsync(file,message + "\n").then(
function () {
win("OK");
},
function (e) {
fail(e);
});
},
function (e) {
fail(e);
})
},
function (e) {
fail(e);
}
);
}
But of course this crashes if there are a lot of incoming log messages (at startup around 800). I also tried to keep the file opened constantly and write to it, but this crashes also. Would something like FileOutputStream be the better option? How would I use it?
Thanks in advance any help is appreciated!
I suggest separating all the code up to FileIO.appendTextAsync so that you cache a StorageFile object. A StorageFile is really just an abstraction for a pathname to allow for files that aren't actually backed by the file system. Keeping a StorageFile in hand, then, does not mean that you're holding the file open. FileIO.appendTextAsync will take care of opening a stream, writing to it, and closing it.
So you can do the getFolderAsync and createFileAsync once instead of doing it with every message. Then I suspect that the appendTextAsync will be able to keep up with your logging traffic. Given that WinRT is written to be thread-safe, the implementation of appendTextAsync should handle concurrency matters just fine. You logging method, then, is just a simple wrapper around appendTextAsync using your cached StorageFile object.
As an alternative, check out the FileLoggingSession class in Windows.Foundation.Diagnostics, which is written exactly to do continuous file-based logging, and also generates binary RTL data that can be brought into the Windows Performance Analyzer and Trace Reporter tools in the Windows SDK. For details, see the FileLoggingSession sample and the Windows Performance Analyzer documentation.