Typescript - Add logic to clean up old logs

This commit is contained in:
Kiran Niranjan 2018-11-30 13:56:25 +05:30
parent 36cc26db8f
commit 8c44c04540
2 changed files with 29 additions and 3 deletions

View File

@ -111,7 +111,6 @@
"jest-html-reporter": "2.4.2",
"less": "3.8.1",
"ncp": "2.0.0",
"react": "^16.6.0",
"robotjs": "0.5.1",
"selenium-webdriver": "3.6.0",
"spectron": "5.0.0",
@ -137,6 +136,7 @@
"lodash.omit": "4.5.0",
"lodash.pick": "4.4.0",
"node-osascript": "2.1.0",
"react": "16.6.3",
"react-dom": "^16.6.0",
"ref": "1.3.5",
"shell-path": "2.1.0",

View File

@ -1,6 +1,8 @@
import { app } from 'electron';
import electronLog, { LogLevel, transports } from 'electron-log';
import * as fs from 'fs';
import * as path from 'path';
import * as util from 'util';
import { isElectronQA } from './env';
import { getCommandLineArgs } from './utils';
@ -24,15 +26,17 @@ export class Logger {
private readonly showInConsole: boolean = false;
private readonly desiredLogLevel?: LogLevel;
private readonly logQueue: ILogMsg[];
private readonly logPath: string;
private loggerWindow: Electron.WebContents | null;
constructor() {
this.loggerWindow = null;
this.logQueue = [];
this.logPath = app.getPath('logs');
if (!isElectronQA) {
transports.file.file = path.join(app.getPath('logs'), 'app.log');
transports.file.file = path.join(this.logPath, 'app.log');
transports.file.level = 'debug';
transports.file.format = '{h}:{i}:{s}:{ms} {text}';
transports.file.maxSize = 10 * 1024 * 1024;
@ -50,6 +54,9 @@ export class Logger {
if (getCommandLineArgs(process.argv, '--enableConsoleLogging', false)) {
this.showInConsole = true;
}
// cleans up old logs if there are any
this.cleanupOldLogs();
}
/**
@ -177,7 +184,7 @@ export class Logger {
*
* @param logMsg {ILogMsg}
*/
private sendToCloud(logMsg: ILogMsg) {
private sendToCloud(logMsg: ILogMsg): void {
// don't send logs if it is not desired by the user
if (this.desiredLogLevel && this.desiredLogLevel !== logMsg.level) {
return;
@ -193,6 +200,25 @@ export class Logger {
}
}
}
/**
* Cleans up logs older than a day
*/
private cleanupOldLogs(): void {
const files = fs.readdirSync(this.logPath);
const deleteTimeStamp = new Date().getTime() + (10 * 24 * 60 * 60 * 1000);
files.forEach((file) => {
if (file === '.DS_Store' || file === 'app.log') {
return;
}
const filePath = path.join(this.logPath, file);
const stat = fs.statSync(filePath);
const fileTimestamp = new Date(util.inspect(stat.mtime)).getTime();
if (fileTimestamp > deleteTimeStamp) {
fs.unlinkSync(filePath);
}
});
}
}
const logger = new Logger();