Skip to content

Commit ec55bfc

Browse files
committed
📣 better logging
1 parent 5738a57 commit ec55bfc

6 files changed

Lines changed: 59 additions & 73 deletions

File tree

app/ipc/ipc_main.ts

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { setMenuBar, showMenuBar, showContextMenu } from '../main_process/menu';
66
import { sendAll } from '../main_process/windowList';
77
import { serverInfo } from '../main_process/server';
88
import { ServerInfo } from '../main_process/types';
9-
import { logLine, logFilePath, LogLevel, LogSource } from '../src/util/log';
9+
import { logFilePath } from '../src/util/log';
1010

1111
ipcMain.handle('open-file', (event, options) => {
1212
const win = BrowserWindow.fromWebContents(event.sender);
@@ -104,8 +104,3 @@ export function exportDebugLog(window: BrowserWindow): void {
104104
ipcMain.handle('get-home-path', () => {
105105
return app.getPath('home');
106106
});
107-
108-
ipcMain.handle('log-line', (_event, source: LogSource, level: LogLevel, ...args: any[]) => {
109-
assertSome(logLine);
110-
logLine(source, level, ...args.map((x) => JSON.stringify(x)));
111-
});

app/main_process/index.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,14 @@ export const createWindow = (): void => {
2424
show: false,
2525
});
2626

27+
let dontSendLog = false;
28+
window.webContents.on('console-message', (_e, level, message) => {
29+
if (message == 'server stderr') dontSendLog = true;
30+
logLine && !dontSendLog && logLine(LogSource.RendererProcess, NumericLogLevels[level], message);
31+
32+
if (message == 'console.groupEnd') dontSendLog = false;
33+
});
34+
2735
window.webContents.on('new-window', (event, url, frameName, disposition, options) => {
2836
if (frameName === 'modal') {
2937
event.preventDefault();
@@ -151,4 +159,4 @@ import './server';
151159
import { windowList } from './windowList';
152160
import { applyMenuBar, setMenuBar } from './menu';
153161
import { isRunningInTest } from '../src/util';
154-
import { initMainProcessLog } from '../src/util/log';
162+
import { LogSource, NumericLogLevels, initMainProcessLog, logLine } from '../src/util/log';

app/main_process/server.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { app, dialog } from 'electron';
66
import { publishServerInfo, publishServerStderr } from '../ipc/ipc_main';
77
import { ServerInfo } from './types';
88
import { isRunningInTest } from '../src/util';
9+
import { LogLevel, LogSource, logLine } from '../src/util/log';
910

1011
function findServer() {
1112
const possibilities = [
@@ -74,7 +75,7 @@ function startServer() {
7475
return;
7576
}
7677
serverProcess.stdout.on('data', (data: Buffer) => {
77-
console.log('server-stdout', data.toString());
78+
logLine && logLine(LogSource.ServerProcess, LogLevel.Log, data);
7879
try {
7980
const parsed_data: ServerStartingMessage | ServerStartedMessage = JSON.parse(data.toString());
8081
if (parsed_data.msg == 'server_starting') {
@@ -88,7 +89,7 @@ function startServer() {
8889
});
8990

9091
serverProcess.stderr.on('data', (data: Buffer) => {
91-
console.log(`server-stderr: \n${data}`);
92+
logLine && logLine(LogSource.ServerProcess, LogLevel.Error, data);
9293
publishServerStderr(data.toString());
9394
});
9495

app/scripts/dev.js

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
1-
const { createServer, build, createLogger } = require('vite');
1+
const { createServer, build } = require('vite');
22
const electronPath = require('electron');
33
const { spawn } = require('child_process');
44
const mode = (process.env.MODE = process.env.MODE || 'development');
5-
const LOG_LEVEL = 'warn';
65
const sharedConfig = {
76
mode,
87
build: {
98
watch: {},
109
},
11-
logLevel: LOG_LEVEL,
10+
logLevel: 'warn',
1211
};
1312

1413
const getWatcher = ({ name, configFile, writeBundle }) => {
@@ -29,10 +28,6 @@ const setupMainPackageWatcher = (viteDevServer) => {
2928
process.env.VITE_DEV_SERVER_URL = `${protocol}//${host}:${port}${path}`;
3029
}
3130

32-
const logger = createLogger(LOG_LEVEL, {
33-
prefix: '[main]',
34-
});
35-
3631
let spawnProcess = null;
3732

3833
return getWatcher({
@@ -44,18 +39,10 @@ const setupMainPackageWatcher = (viteDevServer) => {
4439
spawnProcess = null;
4540
}
4641

47-
spawnProcess = spawn(String(electronPath), [
48-
`${dir}/start.cjs.js`,
49-
`--remote-debugging-port=${process.env.DEBUGGER_PORT}`,
50-
]);
51-
52-
spawnProcess.stdout.on(
53-
'data',
54-
(d) => d.toString().trim() && logger.warn(d.toString(), { timestamp: true })
55-
);
56-
spawnProcess.stderr.on(
57-
'data',
58-
(d) => d.toString().trim() && logger.error(d.toString(), { timestamp: true })
42+
spawnProcess = spawn(
43+
String(electronPath),
44+
[`${dir}/start.cjs.js`, `--remote-debugging-port=${process.env.DEBUGGER_PORT}`],
45+
{ stdio: 'inherit' }
5946
);
6047
},
6148
});

app/src/index.tsx

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,9 @@ import * as ReactDOM from 'react-dom';
44
import './index.css';
55

66
import App from './components/App';
7-
import { exportDebugLogsToDisk, initRendererLog } from './util/log';
7+
import { exportDebugLogsToDisk } from './util/log';
88
import { subscribeExportDebugLog } from '../ipc/ipc_renderer';
99

10-
initRendererLog();
11-
1210
subscribeExportDebugLog((event, mainProcessLogPath) => exportDebugLogsToDisk(mainProcessLogPath));
1311

1412
const anyModule = module as any;

app/src/util/log.ts

Lines changed: 39 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,41 @@
11
import fs, { createWriteStream } from 'fs';
22
import path from 'path';
33
import JSZip from 'jszip';
4-
import { getHomePath, saveFile, sendLogLine } from '../../ipc/ipc_renderer';
4+
import { getHomePath, saveFile } from '../../ipc/ipc_renderer';
55
import { isRunningInTest } from './index';
66
import glob from 'glob';
77
import { app } from 'electron';
88

99
export enum LogLevel {
1010
Log,
11-
Trace,
12-
Debug,
1311
Info,
1412
Warn,
1513
Error,
16-
GroupCollapsed,
17-
GroupEnd,
1814
}
1915

16+
export const NumericLogLevels = [LogLevel.Log, LogLevel.Info, LogLevel.Warn, LogLevel.Error];
17+
2018
export enum LogSource {
2119
MainProcess,
2220
RendererProcess,
21+
ServerProcess,
2322
}
2423

2524
export let logFilePath: string | null = null;
26-
let oldLog: ((...args: any[]) => void) | null = null;
25+
26+
const buffer: string[] = [];
27+
function write(str: string) {
28+
buffer.push(str);
29+
30+
const try_fn = () => {
31+
if (process.stdout.writableLength == 0) {
32+
process.stdout.write(buffer.shift() || '');
33+
} else {
34+
setTimeout(try_fn, 10);
35+
}
36+
};
37+
try_fn();
38+
}
2739

2840
function log(file: number, source: LogSource, level: LogLevel, ...args: any[]) {
2941
const date = new Date().toISOString();
@@ -36,7 +48,23 @@ function log(file: number, source: LogSource, level: LogLevel, ...args: any[]) {
3648
level: level_str,
3749
args: string_args,
3850
});
39-
if (oldLog !== null) oldLog(log_line);
51+
52+
const FgGreen = '\x1b[32m';
53+
const FgBlue = '\x1b[34m';
54+
const FgYellow = '\x1b[33m';
55+
const Reset = '\x1b[0m';
56+
const source_color = [FgGreen, FgBlue, FgYellow][source];
57+
58+
write(
59+
args
60+
.join('\n')
61+
.split('\n')
62+
.map(
63+
(line) =>
64+
`${source_color}[${source_str.substring(0, 4)}]${Reset} ${level_str.padEnd(5)} | ${line}`
65+
)
66+
.join('\n') + '\n'
67+
);
4068
fs.writeSync(file, log_line + '\n');
4169
fs.fsyncSync(file);
4270
}
@@ -64,24 +92,15 @@ export function initMainProcessLog(): void {
6492
logFilePath = path.join(log_dir, fileName);
6593
const file = fs.openSync(logFilePath, 'w');
6694
console.log('Init logging into', logFilePath);
67-
oldLog = console.log;
6895
console.log = (...args) => log(file, LogSource.MainProcess, LogLevel.Log, ...args);
69-
console.trace = (...args) => log(file, LogSource.MainProcess, LogLevel.Trace, ...args);
70-
console.debug = (...args) => log(file, LogSource.MainProcess, LogLevel.Debug, ...args);
96+
console.trace = (...args) => log(file, LogSource.MainProcess, LogLevel.Log, ...args);
97+
console.debug = (...args) => log(file, LogSource.MainProcess, LogLevel.Log, ...args);
7198
console.info = (...args) => log(file, LogSource.MainProcess, LogLevel.Info, ...args);
7299
console.warn = (...args) => log(file, LogSource.MainProcess, LogLevel.Warn, ...args);
73100
console.error = (...args) => log(file, LogSource.MainProcess, LogLevel.Error, ...args);
74101
logLine = (...args) => log(file, ...args);
75-
const oldGroupCollapsed = console.groupCollapsed;
76-
console.groupCollapsed = (...args) => {
77-
log(file, LogSource.MainProcess, LogLevel.GroupCollapsed, ...args);
78-
oldGroupCollapsed(...args);
79-
};
80-
const oldGroupEnd = console.groupEnd;
81-
console.groupEnd = (...args) => {
82-
log(file, LogSource.MainProcess, LogLevel.GroupEnd, ...args);
83-
oldGroupEnd(...args);
84-
};
102+
console.groupCollapsed = () => {};
103+
console.groupEnd = () => {};
85104
}
86105

87106
export async function exportDebugLogsToDisk(file: string): Promise<void> {
@@ -108,25 +127,3 @@ export async function exportDebugLogsToDisk(file: string): Promise<void> {
108127
.on('error', reject);
109128
});
110129
}
111-
112-
type KeyOfType<T, V> = keyof {
113-
[P in keyof T as T[P] extends V ? P : never]: any;
114-
};
115-
116-
function _mapLogFn(key: KeyOfType<typeof console, (...args: any[]) => void>, level: LogLevel) {
117-
const _oldFn: (...args: any[]) => void = console[key];
118-
console[key] = (...args: any[]) => {
119-
_oldFn(...args);
120-
sendLogLine(level, ...args);
121-
};
122-
}
123-
export function initRendererLog(): void {
124-
_mapLogFn('log', LogLevel.Log);
125-
_mapLogFn('trace', LogLevel.Trace);
126-
_mapLogFn('debug', LogLevel.Debug);
127-
_mapLogFn('info', LogLevel.Info);
128-
_mapLogFn('warn', LogLevel.Warn);
129-
_mapLogFn('error', LogLevel.Error);
130-
_mapLogFn('groupCollapsed', LogLevel.GroupCollapsed);
131-
_mapLogFn('groupEnd', LogLevel.GroupEnd);
132-
}

0 commit comments

Comments
 (0)