Skip to content

Instantly share code, notes, and snippets.

@cthos
Created February 5, 2018 17:29
Show Gist options
  • Save cthos/5cb763b3cb8dbb334df3d40917822d51 to your computer and use it in GitHub Desktop.
Save cthos/5cb763b3cb8dbb334df3d40917822d51 to your computer and use it in GitHub Desktop.
Making a really dumb Ionic 3 Filelogger
constructor(platform: Platform) {
platform
.ready()
.then(() => {
// statusBar.overlaysWebView(false);
statusBar.styleDefault();
splashScreen.hide();
this.dumblog.realLog = console;
// Override console cause we're nuts.
console = <any> this.dumblog;
this.init();
});
}
import { Injectable } from '@angular/core';
import { File } from '@ionic-native/file';
import * as moment from 'moment';
import { Platform } from 'ionic-angular';
@Injectable()
export class StupidFilelog {
localConsole: Console;
fileCreated: boolean;
isWriting: boolean;
constructor(private file: File, private platform: Platform) {
// super();
}
public set realLog(log: Console) {
this.localConsole = log;
}
public log(...messages) {
this.writeToLogfile('log', messages);
}
public warn(...message) {
this.writeToLogfile('warn', message);
}
public info(...message) {
this.writeToLogfile('info', message);
}
public error(...message) {
this.writeToLogfile('error', message);
}
private getLogfileDir(): string {
if (this.platform.is('ios')) {
return this.file.documentsDirectory;
}
return this.file.dataDirectory + '/Documents';
}
private createFileIfNotExists() {
if (this.fileCreated) {
return;
}
this.fileCreated = true;
this.isWriting = true;
this.file.createFile(this.getLogfileDir(), 'consolelog.log', false)
.then(() => {this.isWriting = false; this.localConsole.log('Created logfile.')})
.catch((e: Error) => {this.isWriting = false; this.localConsole.log('Failed to create logfile.'); this.localConsole.log(e.toString())});
}
protected writeToLogfile(level, messages: any[]) {
this.createFileIfNotExists();
messages.forEach((message) => {
if (!this.platform.is('cordova')) {
return this.localConsole[level](message);
}
try {
message = JSON.stringify(message).substr(0, 500);
} catch (e) {
message = 'LOG Omitted - cyclical JSON.';
}
const timestamp = moment().format();
const line = `${timestamp} : [${level}] - ${message} \n`;
let interval = setInterval(() => {
if (this.isWriting) {
return;
}
this.isWriting = true;
this.writeLogLine(line);
clearInterval(interval);
}, 20);
});
}
protected writeLogLine(line) {
this.file.writeFile(this.getLogfileDir(), 'consolelog.log', line, {append: true})
.then(() => {
this.isWriting = false;
})
.catch((e) => {this.localConsole.log('Failed to write logline. Error: ', e); this.isWriting = false; });
}
}
@chrisweight
Copy link

Brilliant! Just what I need!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment