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

fix: server web logging running server #3408

Merged
merged 3 commits into from
Dec 8, 2024
Merged
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
3 changes: 2 additions & 1 deletion apps/server-web/src/main/helpers/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ export const ServerPageTypeMessage = {

export const LOG_TYPES = {
UPDATE_LOG: 'UPDATE-LOG',
SERVER_LOG: 'SERVER-LOG'
SERVER_LOG: 'SERVER-LOG',
SERVER_LOG_ERROR: 'SERVER-LOG-ERROR'
}

export const IPC_TYPES: {
Expand Down
45 changes: 29 additions & 16 deletions apps/server-web/src/main/helpers/services/libs/server-task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,8 @@ export abstract class ServerTask {

this.loggerObserver = new Observer((msg: string) => {
console.log('Sending log_state:', msg);
if (!this.window?.isDestroyed()) {
// this.window.webContents.send('log_state', { msg });
}
const logType = this.isErrorMessage(msg) ? LOG_TYPES.SERVER_LOG_ERROR : LOG_TYPES.SERVER_LOG;
console.log(logType, msg);
});

this.stateObserver = new Observer((state: boolean) => {
Expand All @@ -64,6 +63,11 @@ export abstract class ServerTask {
});
}

private isErrorMessage(msg: string): boolean {
return msg.includes('stderr:') ||
this.criticalMessageError.some(error => msg.includes(error));
}

protected async runTask(signal: AbortSignal): Promise<void> {
console.log('Run Server Task');
return new Promise<void>((resolve, reject) => {
Expand All @@ -72,16 +76,20 @@ export abstract class ServerTask {

const service = ChildProcessFactory.createProcess(this.processPath, this.args, signal);

console.log(LOG_TYPES.SERVER_LOG, 'Service created', service.pid);
this.loggerObserver.notify(`Service created ${service.pid}`)

service.stdout?.on('data', (data: any) => {
const msg = data.toString();
this.loggerObserver.notify(msg);
if (msg.includes(this.successMessage)) {
const name = String(this.args.serviceName);
this.stateObserver.notify(true);
console.log(this.args)
this.loggerObserver.notify(
`☣︎ ${name.toUpperCase()} server listen to ${this.config.setting[`${name}Url`]}`
`☣︎ ${name.toUpperCase()} running on http://${this.args.DESKTOP_WEB_SERVER_HOSTNAME}:${this.args.PORT}`
);
this.loggerObserver.notify(
`☣︎ ${name.toUpperCase()} connected to api ${this.args.GAUZY_API_SERVER_URL}`
);
resolve();
}
Expand All @@ -92,20 +100,12 @@ export abstract class ServerTask {
}
});

service.stderr?.on('data', (data: any) => {
console.log(LOG_TYPES.SERVER_LOG, 'stderr:', data.toString());
this.loggerObserver.notify(data.toString());
});
service.stderr?.on('data', this.handleStdErr.bind(this));

service.on('disconnect', () => {
console.log(LOG_TYPES.SERVER_LOG, 'Webserver disconnected');
if (this.eventEmitter) {
this.eventEmitter.emit(EventLists.webServerStopped);
}
})
service.on('disconnect', this.handleDisconnect.bind(this));

service.on('error', (err) => {
console.log('child process error', err);
this.handleError(err, false);
})

if (this.eventEmitter) {
Expand Down Expand Up @@ -168,6 +168,19 @@ export abstract class ServerTask {
}
}

private handleStdErr(data: any): void {
const errorMessage: string = data.toString();
this.loggerObserver.notify(`stderr: ${errorMessage}`);
}

private handleDisconnect(): void {
this.loggerObserver.notify('Webserver disconnected')
if (this.eventEmitter) {
this.eventEmitter.emit(EventLists.webServerStopped);
}
this.stateObserver.notify(false);
}

protected handleError(error: any, attemptKill = true) {
if (attemptKill) {
this.kill(false); // Pass false to indicate that handleError should not attempt to kill again
Expand Down
10 changes: 10 additions & 0 deletions apps/server-web/src/main/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,16 @@ Log.hooks.push((message: any, transport) => {
}
}

if (message.data[0] === LOG_TYPES.SERVER_LOG_ERROR) {
if (logWindow) {
const msg = message.data.join(' ');
logWindow.webContents.send(IPC_TYPES.SERVER_PAGE, {
type: LOG_TYPES.SERVER_LOG_ERROR,
msg
});
}
}

if (message.data[0] === LOG_TYPES.UPDATE_LOG) {
if (settingWindow) {
const msg = `${message.data.join(' ')}`;
Expand Down
61 changes: 54 additions & 7 deletions apps/server-web/src/renderer/pages/Server.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,54 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useRef, ReactNode } from 'react';
import { ServerPageTypeMessage } from '../../main/helpers/constant';
import { IPC_TYPES, LOG_TYPES } from '../../main/helpers/constant';
import { EverTeamsLogo } from '../components/svgs';
import { useTranslation } from 'react-i18next';

const LogView = ({ children }: { children: ReactNode }) => {
return <div className="py-1">{children}</div>;
};

export function ServerPage() {
const logRef = useRef<HTMLDivElement>(null);
const [isRun, setIsRun] = useState<boolean>(false);
const [logs, setLogs] = useState<string[]>([]);
const [logs, setLogs] = useState<
{
message: string;
type: 'error-log' | 'log';
}[]
>([]);
const [loading, setLoading] = useState<boolean>(false);
const { t } = useTranslation();
const [logOpen, setLogOpen] = useState<boolean>(false);

useEffect(() => {
window.electron.ipcRenderer.removeEventListener(IPC_TYPES.SERVER_PAGE);
window.electron.ipcRenderer.on(IPC_TYPES.SERVER_PAGE, (arg: any) => {
switch (arg.type) {
case LOG_TYPES.SERVER_LOG:
setLogs((prev) => [...prev, arg.msg]);
setLogs((prev) => [
...prev,
{
message: arg.msg,
type: 'log',
},
]);
scrollToLast();
break;
case LOG_TYPES.SERVER_LOG_ERROR:
setLogs((prev) => [
...prev,
{
message: arg.msg,
type: 'error-log',
},
]);
scrollToLast();
break;
Comment on lines +29 to +46
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Refactor log handling to reduce duplication.

The log handling logic for both normal and error logs is duplicated. Consider extracting it into a helper function.

+const addLog = (prev: typeof logs, message: string, type: 'log' | 'error-log') => [
+  ...prev,
+  { message, type }
+];

-setLogs((prev) => [
-  ...prev,
-  {
-    message: arg.msg,
-    type: 'log',
-  },
-]);
+setLogs((prev) => addLog(prev, arg.msg, 'log'));

Committable suggestion skipped: line range outside the PR's diff.

case ServerPageTypeMessage.SERVER_STATUS:
if (arg.data.isRun) {
setIsRun(true);
setLogOpen(true);
} else {
setIsRun(false);
}
Expand All @@ -41,6 +70,12 @@ export function ServerPage() {
});
};

const scrollToLast = () => {
logRef.current?.scrollIntoView({
behavior: 'smooth',
});
};

return (
<div className="min-h-screen flex flex-col flex-auto flex-shrink-0 antialiased text-gray-800">
<div className="rounded-lg px-16 py-10">
Expand All @@ -60,7 +95,14 @@ export function ServerPage() {
</button>
<div className="grid divide-y divide-neutral-200 dark:bg-[#25272D] dark:text-white mx-auto w-10/12 rounded-lg border-2 border-gray-200 dark:border-gray-600">
<div className="py-5 px-5">
<details className="group">
<details
className="group"
open={logOpen}
onClick={(e) => {
e.preventDefault();
setLogOpen((prev) => !prev);
}}
>
<summary className="flex justify-between items-center font-medium cursor-pointer list-none">
<span className="p-2"> Server Logs</span>
<span className="transition group-open:rotate-180">
Expand Down Expand Up @@ -90,11 +132,16 @@ export function ServerPage() {
<div className="ml-1 mt-1 p-2">
{logs.length > 0 &&
logs.map((log, i) => (
<div className="py-1" key={i}>
<span>{log}</span>
</div>
<LogView key={i}>
{log.type === 'error-log' ? (
<span className="text-red-600">{log.message}</span>
) : (
<span className="text-white">{log.message}</span>
)}
</LogView>
))}
Comment on lines +135 to +141
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Avoid using array index as key.

Using array index as key prop can lead to rendering issues when logs are added or removed.

Consider adding a timestamp or unique ID to each log entry:

-logs.map((log, i) => (
-  <LogView key={i}>
+logs.map((log) => (
+  <LogView key={`${log.type}-${Date.now()}`}>

Committable suggestion skipped: line range outside the PR's diff.

</div>
<div className="py-1" ref={logRef}></div>
</div>
</details>
</div>
Expand Down
Loading