Skip to content

Commit

Permalink
fix(logging): Logging prefix (#66)
Browse files Browse the repository at this point in the history
* Removed debug from dev-test-server

* Added ability to send child logs to internal logger

* Made file naming clearer and added logger definition to childTask

* Updated namings and added logger to childTasks

* Removed extraneous logging at the end

* Fixed dev-test-server script params

* Added logging to stderr as well

* Refactored logger to direct use

* ESLint cleanup

* Added stream handler to logger

* commenting

* Better prop naming
  • Loading branch information
mikkotikkanen authored May 11, 2021
1 parent d04a41e commit e95da5f
Show file tree
Hide file tree
Showing 12 changed files with 197 additions and 141 deletions.
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ services:
environment:
- "NODE_ENV=development"
- "FORCE_COLOR=1"
command: "npm run dev-test-server -- --polling"
command: "npm run dev-test-server -- --legacywatch"

volumes:
node_modules_data:
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"monitor",
"restart",
"development",
"typescript"
"typescript",
"docker"
],
"author": {
"name": "Mikko Tikkanen",
Expand Down Expand Up @@ -55,7 +56,7 @@
},
"scripts": {
"dev": "tsc --watch",
"dev-test-server": "ts-node ./src/bin/cli.ts ./dist/test/apps/test-server.js --debug",
"dev-test-server": "ts-node ./src/bin/cli.ts ./dist/test/apps/test-server.js",
"dev-test-lib": "ts-node ./src/bin/cli.ts",
"dev-test-help": "ts-node ./src/bin/cli.ts --help",
"dev-test-version": "ts-node ./src/bin/cli.ts --version",
Expand All @@ -67,4 +68,4 @@
"prepublishOnly": "npm run build",
"release": "semantic-release"
}
}
}
7 changes: 2 additions & 5 deletions src/lib/EventBus/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import EventEmitter from 'events';
import logger from '../logger/logger';

export type EventBusProps = {
/**
Expand All @@ -11,10 +12,6 @@ export enum ProcessEvents {
Start = 'PROCESS_START',
}

export enum LogEvents {
Message = 'LOG_MESSAGE',
}

export enum ChildEvents {
Start = 'CHILD_START',
Started = 'CHILD_STARTED',
Expand Down Expand Up @@ -53,7 +50,7 @@ export default class EventBus extends EventEmitter {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
emit(event: string, ...args: any[]): boolean {
if (this.debug) {
super.emit(LogEvents.Message, `Eventbus event emit. "${event}"`);
logger.prefix(`Eventbus event emit. "${event}"`);
}

return super.emit(event, ...args);
Expand Down
32 changes: 31 additions & 1 deletion src/lib/child/Run.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { spawn } from 'child_process';
import kill from 'tree-kill';
import EventBus from '../EventBus';
import logger from '../logger/logger';


export interface RunProps {
Expand All @@ -14,6 +15,11 @@ export interface RunProps {
*/
cwd?: string;

/**
* Whether to prefix logs or not
*/
prefixLogs?: boolean;

/**
* Should the process be started automatically
*/
Expand All @@ -30,6 +36,7 @@ export enum Events {
Started = 'RUN_STARTED',
Stop = 'RUN_STOP',
Stopped = 'RUN_STOPPED',
Log = 'RUN_LOG',
}


Expand All @@ -38,6 +45,8 @@ export class Run {

private cwd?: string;

private prefixLogs: boolean;

private pid = 0;

readonly Events = Events;
Expand All @@ -47,11 +56,13 @@ export class Run {
constructor({
command,
cwd,
prefixLogs = false,
autostart = true,
debug = false,
}: RunProps) {
this.command = command;
this.cwd = cwd;
this.prefixLogs = prefixLogs;
this.eventBus = new EventBus({
debug,
});
Expand All @@ -78,22 +89,41 @@ export class Run {
return this.pid !== 0;
}

log(message: string): void {
if (this.prefixLogs) {
logger.prefix(message);
} else {
logger.log(message);
}
}

start(): void {
// Start child process
const child = spawn(this.command, { // child event handlers are left behind after restart
cwd: this.cwd,
shell: true,
stdio: 'inherit',
stdio: 'pipe',
});
this.pid = child.pid;

// Log process output
if (this.prefixLogs) {
logger.prefixStream(child.stdout);
logger.prefixStream(child.stderr);
} else {
logger.logStream(child.stdout);
logger.logStream(child.stderr);
}

// When child exists, send corresponding event to eventbus
child.on('close', (code: number) => {
if (this.pid) {
this.pid = 0;
this.eventBus.emit(this.Events.Stopped, code);
}
});

// Notify eventbus that child has started when everything is set
this.eventBus.emit(this.Events.Started);
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import EventBus, { ChildEvents } from '../EventBus';
import { Run } from './Run';

type runRestartableProps = {
type childProcessProps = {
/**
* Event bus
*/
Expand All @@ -19,7 +19,7 @@ let isRestarting = false;
export default ({
eventBus,
command,
}: runRestartableProps): void => {
}: childProcessProps): void => {
const run = new Run({ command });

run.eventBus.on(run.Events.Started, () => {
Expand Down
10 changes: 9 additions & 1 deletion src/lib/child/childRun.ts → src/lib/child/childTask.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import logger from '../logger/logger';
import { Run } from './Run';

export default (command: string): Promise<void> => new Promise((resolve, reject) => {
const run = new Run({ command });
const run = new Run({
command,
prefixLogs: true,
});

run.eventBus.on(run.Events.Stopped, (code) => {
if (code) {
Expand All @@ -11,5 +15,9 @@ export default (command: string): Promise<void> => new Promise((resolve, reject)
}
});

run.eventBus.on(run.Events.Log, (message) => {
logger.log(message);
});

run.start();
});
6 changes: 3 additions & 3 deletions src/lib/child/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import runRestartable from './childRunRestartable';
import runOnce from './childRun';
import childProcess from './childProcess';
import childTask from './childTask';

export { runOnce, runRestartable };
export { childTask, childProcess };
33 changes: 25 additions & 8 deletions src/lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import treeKill from 'tree-kill';
import { existsSync } from 'fs';
import { join } from 'path';
import modules from './modules';
import watch from './watch';
import { runRestartable } from './child';
import logger from './logger';
import { childProcess } from './child';
import EventBus, {
ChildEvents,
ModulesEvents,
ProcessEvents,
WatchEvents,
} from './EventBus';
import logger from './logger/logger';
import loadPackageJSON from './modules/loadPackageJSON';


export interface LibProps {
Expand Down Expand Up @@ -78,6 +80,10 @@ export interface LibProps {
let isStarted = false;
let isBeingKilled = false;

const pckg = loadPackageJSON(join(__dirname, '..', '..', 'package.json'));
if (!pckg) {
throw new Error('Failed to load module package.json');
}

/**
* Setup main process
Expand All @@ -104,11 +110,8 @@ export default ({
throw new Error(`Path "${watchdir}" does not exist.`);
}

if (logging) {
logger({
eventBus,
});
}
// Enable/disable logger
logger.enabled(logging);

const props: LibProps = {
command,
Expand Down Expand Up @@ -159,7 +162,7 @@ export default ({


// Setup the requested command
runRestartable({
childProcess({
eventBus,
command: `${exec} ${command}`,
});
Expand All @@ -183,6 +186,20 @@ export default ({
eventBus.on(ChildEvents.Stop, () => {
isBeingKilled = true;
});
eventBus.on(ChildEvents.Stopped, () => {
logger.prefix('Child process exited.');
});

logger.prefix();
logger.prefix(`v${pckg.version}`);
logger.prefix(`Child process: ${exec} ${command}`);
logger.prefix(`Watching directory: ${watchdir}`);
logger.prefix(`Watching extensions: ${ext?.join(',')}`);
logger.prefix(`Watch delay: ${delay}ms`);
if (legacywatch) {
logger.prefix('Using legacywatch');
}
logger.prefix();

return eventBus;
};
Expand Down
108 changes: 0 additions & 108 deletions src/lib/logger/index.ts

This file was deleted.

Loading

0 comments on commit e95da5f

Please sign in to comment.