log to stderr when running on node

This commit is contained in:
Florian Dold 2020-03-26 20:35:06 +05:30
parent ccdc7cffed
commit 3d0fbea467
No known key found for this signature in database
GPG Key ID: D2E4F00F29D02A4B
2 changed files with 68 additions and 5 deletions

View File

@ -14,18 +14,74 @@
TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
/**
* Imports.
*/
import { isNode } from "../webex/compat";
function writeNodeLog(
message: string,
tag: string,
level: string,
args: any[],
) {
process.stderr.write(`${new Date().toISOString()} ${tag} ${level} `);
process.stderr.write(message);
if (args.length != 0) {
process.stderr.write(" ");
process.stderr.write(JSON.stringify(args, undefined, 2));
}
process.stderr.write("\n");
}
/**
* Logger that writes to stderr when running under node,
* and uses the corresponding console.* method to log in the browser.
*/
export class Logger {
constructor(private tag: string) {}
info(message: string, ...args: any[]) {
console.log(`${new Date().toISOString()} ${this.tag} INFO ` + message, ...args);
if (isNode()) {
writeNodeLog(message, this.tag, "INFO", args);
} else {
console.info(
`${new Date().toISOString()} ${this.tag} INFO ` + message,
...args,
);
}
}
warn(message: string, ...args: any[]) {
console.log(`${new Date().toISOString()} ${this.tag} WARN ` + message, ...args);
if (isNode()) {
writeNodeLog(message, this.tag, "WARN", args);
} else {
console.warn(
`${new Date().toISOString()} ${this.tag} INFO ` + message,
...args,
);
}
}
error(message: string, ...args: any[]) {
console.log(`${new Date().toISOString()} ${this.tag} ERROR ` + message, ...args);
if (isNode()) {
writeNodeLog(message, this.tag, "ERROR", args);
} else {
console.info(
`${new Date().toISOString()} ${this.tag} ERROR ` + message,
...args,
);
}
}
trace(message: any, ...args: any[]) {
console.log(`${new Date().toISOString()} ${this.tag} TRACE ` + message, ...args)
if (isNode()) {
writeNodeLog(message, this.tag, "TRACE", args);
} else {
console.info(
`${new Date().toISOString()} ${this.tag} TRACE ` + message,
...args,
);
}
}
}
}

View File

@ -26,3 +26,10 @@ export function isFirefox(): boolean {
}
return false;
}
/**
* Check if we are running under nodejs.
*/
export function isNode() {
return (typeof process !== 'undefined') && (process.release.name === 'node')
}