Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rotating log file for #1534 #1596

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions packages/main/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"music-metadata": "^7.12.3",
"node-fetch": "^2.6.0",
"reflect-metadata": "^0.1.13",
"rotating-file-stream": "^2.0.2",
"rotating-file-stream": "^3.2.1",
"sqlite3": "^5.1.2",
"stream-filter": "^2.1.0",
"stream-reduce": "^1.0.3",
Expand Down Expand Up @@ -96,4 +96,4 @@
"mpris-service": "2.1.0",
"x11": "^2.3.0"
}
}
}
28 changes: 17 additions & 11 deletions packages/main/src/services/logger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,10 @@
import { app } from 'electron';
import timber from 'electron-timber';
import path from 'path';
import * as rts from 'rotating-file-stream';
import {RotatingFileStream, createStream} from 'rotating-file-stream';

timber.hookConsole();

const errorLogStream = rts.createStream(
path.join(app.getPath('userData'), 'logs', 'nuclear-error.log'),
{
size: '5M',
compress: 'gzip'
}
);

/**
* @see {@link https://github.com/sindresorhus/electron-timber}
Expand All @@ -34,10 +27,19 @@ export interface ILogger {
class Logger implements ILogger {
private logger: typeof timber;
private name: string;
private errorLogStream: RotatingFileStream;

constructor(name?: string) {
this.name = name || 'main';
this.logger = name ? timber.create({ name }) : timber;
this.errorLogStream = createStream(
path.join(app.getPath('userData'), 'logs', 'nuclear-error.log'),
{
size: '1M',
compress: 'gzip',
rotate: 5 // arbitrary value to specify the number of rotations
}
);
}

private getDate() {
Expand All @@ -54,15 +56,19 @@ class Logger implements ILogger {
writeToFile(name: string, ...args: any[]) {
args.forEach((log) => {
if (log.stack) {
errorLogStream.write(`${this.getDate()}${name} > ${log.stack}`);
this.errorLogStream.write(`${this.getDate()}${name} > ${log.stack}`);
} else if (log.message) {
errorLogStream.write(`${this.getDate()}${name} > ${log.message}\n`);
this.errorLogStream.write(`${this.getDate()}${name} > ${log.message}\n`);
} else if (log.toString) {
errorLogStream.write(`${this.getDate()}${name} > ${log.toString()}\n`);
this.errorLogStream.write(`${this.getDate()}${name} > ${log.toString()}\n`);
}
});
}

getErrorLogStream() {
return this.errorLogStream;
}

log(...args: any[]): void {
this.logger.log(...args);
}
Expand Down
71 changes: 71 additions & 0 deletions packages/main/src/services/logger/logger.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import Logger from '.';

jest.mock('electron-timber', () => ({
error: jest.fn(),
hookConsole: jest.fn()
}));

jest.mock('electron', () => ({
app: {
getPath: jest.fn().mockImplementation(() => '/user/data')
}
}));


jest.mock('fs/promises', () => {
const writeFileMock = jest.fn();
const closeFileMock = jest.fn();
return ({
open: jest.fn().mockResolvedValue({
write: jest.fn(),
close: jest.fn()
}),
stat: jest.fn().mockResolvedValue({
isFile: jest.fn().mockReturnValue(true),
size: 0
}),
writeFile: jest.fn().mockResolvedValue({}),
mkdir: jest.fn().mockResolvedValue({}),
closeFileMock,
writeFileMock
});
});

jest.mock('fs', () => ({
constants: jest.requireActual('fs').constants,
access: jest.fn().mockResolvedValue({}),
createReadStream: jest.fn(() => ({
once: jest.fn(),
pipe: jest.fn(() => ({
...jest.requireActual('stream').Writable.prototype,
write: jest.fn(),
end: jest.fn(),
emit: jest.fn()
}))
})),
createWriteStream: jest.fn(() => ({
once: jest.fn(),
emit: jest.fn()
}))
}));

describe('logger', () => {
let logger: Logger;

it('creates a file for logs', async () => {
logger = new Logger();
const errorLogStream = logger.getErrorLogStream();
await new Promise((resolve) => {
errorLogStream.on('open', () => {
resolve(0);
}
);
});

const fsPromises = await import('fs/promises');
logger.error(new Error('test error'));

expect(fsPromises.stat).toHaveBeenCalledWith('/user/data/logs/nuclear-error.log');
expect(fsPromises.open).toHaveBeenCalledWith('/user/data/logs/nuclear-error.log', 'a', undefined);
});
});