I want to add some simple logging capabilities to my cordova app.
So I added the file plugin, implemented a super simple log method and tested.
My configuration:
$ cordova --version
3.5.0-0.2.7
$ cordova plugins
org.apache.cordova.file 1.3.0 "File"
The test device is a Huawei u8850, running Android 2.3.5
The Logger:
window.MyLog = {
log: function(line){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(FS) {
FS.root.getFile('the_log1.txt', {"create":true, "exclusive":false},
function(fileEntry) {
fileEntry.createWriter(
function(writer) {
console.log(line);
writer.seek(writer.length); // append to eof
writer.write(line + '\n'); // write the line
}, fail);
}, fail);
}, fail);
}
};
Testing:
MyLog.log(new Date().toLocaleTimeString());
All seems fine:
But then: I tried to write some extra chars:
window.MyLog = {
log: function(line){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(FS) {
FS.root.getFile('the_log2.txt', {"create":true, "exclusive":false},
function(fileEntry) {
fileEntry.createWriter(
function(writer) {
console.log(line);
writer.seek(writer.length); // append to eof
writer.write(line + '\n'); // write the line
writer.write('----' + '\n'); // extra write
}, fail);
}, fail);
}, fail);
}
};
I found this log cat output:
16:00:00
processMessage failed: Error: [object Object]
processMessage failed: Stack: undefined
processMessage failed: Message: S01 File218896726 {"lastModifiedDate":1409839200000,"fullPath":"\/the_log2.txt","type":"text\/plain","name":"the_log2.txt","size":0}
-> seemingly it is not possible to use the writer.write command more than once
Q:
I think you have to implement and wait for the onwriteend()
event to fire after writing anything to a file.
Once the onwriteend()
fired you can write again to the file.
What I was doing when I created a logging feature was something like this (you can use it as a guide, i'm just typing it out of my head):
function fileItemSuccessWrite(writer){
writer.seek(writer.length);
writer.onwriteend = function(e) {
// TODO WRITE AGAIN
};
writer.onerror = function(e) {
// HANDLE ERROR
};
writer.write(YOUR_LOG_TO_WRITE);
}
fileEntry.createWriter(fileItemSuccessWrite, fileItemFailWrite);
Also what I have created was a cache
(a tmp_variable
) for the content I wanted to write in a log file. Once this tmp_variable
reached a specific size I dumped it in the log file. So it was lighter on fileSystem
access.
You can read about the writer
and write
on W3.org