nestlogger
nestlogger copied to clipboard
Infinite restart after PM2 turns on the watch attribute.
Let's reproduce the bug in a minimal form.
nest creat new-project
// Create a file: logger.ts .
import { Logger } from '@nestjs/common';
export let log: Console | Logger | any = console;
export function setLogger(logger: Console | Logger | any) {
log = logger;
}
// In main.ts add these codes.
async function bootstrap() {
const app = await NestFactory.create(AppModule);
log.log('The application is starting...');
const logger = new Logger('main');
logger.warn('The application logger has been set...');
setLogger(logger);
log.warn('The application log has been set...');
await app.listen(3000);
}
// Create the ecosystem.config.js file for pm2 startup configuration
module.exports = {
apps: [
{
name: 'pm2-test',
script: './dist/main.js',
min_uptime: '60s',
restart_delay: 1000,
autorestart: true,
max_memory_restart: '1G',
watch: ['src'],
ignore_watch: ['node_modules', 'logs'],
watch_delay: 1000,
env_dev: {
NODE_ENV: 'dev',
APP_ENV: 'dev',
watch: true,
},
env_prod: {
NODE_ENV: 'prod',
APP_ENV: 'prod',
watch: false,
},
env_test: {
NODE_ENV: 'test',
APP_ENV: 'test',
watch: true,
},
},
],
};
// Add scripts to package.json .
"start:pm2-dev": "APP_ENV=dev pm2 start ecosystem.config.js --env dev"
ok, now run pnpm run start:pm2-dev, the program is completely normal, there is no problem.
An error occurred !
// Create a file: logger.module.ts and pnpm i nest-logger
import { Global, Module } from '@nestjs/common';
import { LoggerService } from 'nest-logger';
@Global()
@Module({
exports: [LoggerService],
imports: [],
providers: [LoggerService],
})
export default class LoggerModule {}
Then import the LoggerModule in the app module.
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import LoggerModule from './logger.module';
@Module({
imports: [LoggerModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
Now, delete all pm2-running services or delete the pm2 process of the current service, then recompile the code and run it through pm2 again.
You will find that pm2 starts to restart infinitely, the program has no errors, and the log object is used normally, but it will restart continuously.
If you do not import the module where LoggerService is located, the program will run normally. If you turn off the watch property of pm2, the program will run normally, otherwise it will cause infinite restarts without any errors.