mirror of
https://github.com/zulip/zulip-desktop.git
synced 2025-11-15 11:21:51 +00:00
logger: add console helper to log for both file and console
This commit is contained in:
69
app/renderer/js/console.js
Normal file
69
app/renderer/js/console.js
Normal file
@@ -0,0 +1,69 @@
|
||||
const NodeConsole = require('console').Console;
|
||||
const fs = require('fs');
|
||||
|
||||
const { app } = require('electron').remote;
|
||||
const isDev = require('electron-is-dev');
|
||||
|
||||
const browserConsole = console;
|
||||
const logDir = `${app.getPath('userData')}/Logs`;
|
||||
if (!fs.existsSync(logDir)) {
|
||||
fs.mkdirSync(logDir);
|
||||
}
|
||||
|
||||
function customConsole(opts, type, ...args) {
|
||||
const { nodeConsole, timestamp } = opts;
|
||||
if (timestamp) {
|
||||
args.unshift(timestamp());
|
||||
}
|
||||
|
||||
if (!isDev) {
|
||||
const nodeConsoleLog = nodeConsole[type] || nodeConsole.log;
|
||||
nodeConsoleLog.apply(null, args);
|
||||
}
|
||||
browserConsole[type].apply(null, args);
|
||||
}
|
||||
|
||||
function getTimestamp() {
|
||||
const date = new Date();
|
||||
const timestamp =
|
||||
`${date.getMonth()}/${date.getDate()} ` +
|
||||
`${date.getMinutes()}:${date.getSeconds()}`;
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
function setConsoleProto(type) {
|
||||
Object.defineProperty(this, type, {
|
||||
value(...args) {
|
||||
const { timestamp, nodeConsole } = this;
|
||||
const opts = {
|
||||
timestamp,
|
||||
nodeConsole
|
||||
};
|
||||
customConsole.apply(null, [].concat(opts, type, args));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
class Console {
|
||||
constructor(opts = {}) {
|
||||
let { timestamp, file } = opts;
|
||||
file = `${logDir}/${file || 'console.log'}`;
|
||||
if (timestamp === true) {
|
||||
timestamp = getTimestamp;
|
||||
}
|
||||
|
||||
const fileStream = fs.createWriteStream(file);
|
||||
const nodeConsole = new NodeConsole(fileStream);
|
||||
this.nodeConsole = nodeConsole;
|
||||
this.timestamp = timestamp;
|
||||
this.setUpConsole();
|
||||
}
|
||||
|
||||
setUpConsole() {
|
||||
for (const type in browserConsole) {
|
||||
setConsoleProto.call(this, type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Console;
|
||||
Reference in New Issue
Block a user