Skip to content

Commit

Permalink
feat: Unification framework logger (#4236)
Browse files Browse the repository at this point in the history
* feat: use different framework logger

* chore: update code

* feat: use different framework logger

* feat: use different framework logger

* fix: web logger

* fix: framework logger name

* fix: socket case

* fix: lint

* chore: revert

* chore: Use the standard logger
  • Loading branch information
czy88840616 authored Dec 22, 2024
1 parent b504366 commit 9632927
Show file tree
Hide file tree
Showing 27 changed files with 506 additions and 850 deletions.
9 changes: 4 additions & 5 deletions packages/bull/src/config/config.default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,16 @@ export const bull = {
},
defaultConcurrency: 1,
clearRepeatJobWhenStart: true,
contextLoggerApplyLogger: 'bullLogger',
contextLoggerFormat: info => {
const { jobId, from } = info.ctx;
return `${info.timestamp} ${info.LEVEL} ${info.pid} [${jobId} ${from.name}] ${info.message}`;
},
};

export const midwayLogger = {
clients: {
bullLogger: {
fileLogName: 'midway-bull.log',
contextFormat: info => {
const { jobId, from } = info.ctx;
return `${info.timestamp} ${info.LEVEL} ${info.pid} [${jobId} ${from.name}] ${info.message}`;
},
},
},
};
8 changes: 2 additions & 6 deletions packages/bull/src/framework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import {
Framework,
Utils,
MidwayInvokeForbiddenError,
ILogger,
Logger,
DecoratorManager,
MetadataManager,
} from '@midwayjs/core';
Expand Down Expand Up @@ -44,9 +42,7 @@ export class BullFramework
private bullDefaultConcurrency: number;
private bullClearRepeatJobWhenStart: boolean;
private queueMap: Map<string, BullQueue> = new Map();

@Logger('bullLogger')
protected bullLogger: ILogger;
protected frameworkLoggerName = 'bullLogger';

async applicationInitialize(options: IMidwayBootstrapOptions) {
this.app = {} as any;
Expand Down Expand Up @@ -119,7 +115,7 @@ export class BullFramework
);
this.queueMap.set(name, queue);
queue.on('error', err => {
this.bullLogger.error(err);
this.logger.error(err);
});
return queue;
}
Expand Down
30 changes: 15 additions & 15 deletions packages/core/src/baseFramework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,8 @@ export abstract class BaseFramework<
public app: APP;
public configurationOptions: OPT;
protected logger: ILogger;
protected appLogger: ILogger;
protected frameworkLoggerName = 'appLogger';
protected defaultContext = {};
protected contextLoggerApplyLogger: string;
protected contextLoggerFormat: any;
protected middlewareManager = this.createMiddlewareManager();
protected filterManager = this.createFilterManager();
protected guardManager = this.createGuardManager();
Expand Down Expand Up @@ -81,13 +79,9 @@ export abstract class BaseFramework<
constructor(readonly applicationContext: IMidwayGlobalContainer) {}

@Init()
async init() {
protected async init() {
this.configurationOptions = this.configure() ?? ({} as OPT);
this.contextLoggerApplyLogger =
this.configurationOptions.contextLoggerApplyLogger ?? 'appLogger';
this.contextLoggerFormat = this.configurationOptions.contextLoggerFormat;
this.logger = this.loggerService.getLogger('coreLogger');
this.appLogger = this.loggerService.getLogger('appLogger');
return this;
}

Expand All @@ -97,7 +91,7 @@ export abstract class BaseFramework<
): void | Promise<void>;
public abstract run(): Promise<void>;

isEnable(): boolean {
public isEnable(): boolean {
return true;
}

Expand Down Expand Up @@ -133,7 +127,7 @@ export abstract class BaseFramework<
}

protected createContextLogger(ctx: CTX, name?: string): ILogger {
if (name && name !== 'appLogger') {
if (name && name !== this.frameworkLoggerName) {
const appLogger = this.getLogger(name);
let ctxLoggerCache = ctx.getAttr(REQUEST_CTX_LOGGER_CACHE_KEY) as Map<
string,
Expand All @@ -153,14 +147,12 @@ export abstract class BaseFramework<
ctxLoggerCache.set(name, ctxLogger);
return ctxLogger;
} else {
const appLogger = this.getLogger(name ?? this.contextLoggerApplyLogger);
// avoid maximum call stack size exceeded
if (ctx['_logger']) {
return ctx['_logger'];
}
ctx['_logger'] = this.loggerService.createContextLogger(ctx, appLogger, {
contextFormat: this.contextLoggerFormat,
});
const appLogger = this.getLogger(name);
ctx['_logger'] = this.loggerService.createContextLogger(ctx, appLogger);
return ctx['_logger'];
}
}
Expand Down Expand Up @@ -377,7 +369,7 @@ export abstract class BaseFramework<
}

public getLogger(name?: string) {
return this.loggerService.getLogger(name) ?? this.appLogger;
return this.loggerService.getLogger(name ?? this.frameworkLoggerName);
}

public getCoreLogger() {
Expand Down Expand Up @@ -441,4 +433,12 @@ export abstract class BaseFramework<
public getNamespace() {
return this.namespace;
}

/**
* Set the default framework logger name
* @since 4.0.0
*/
public setFrameworkLoggerName(loggerName: string) {
this.frameworkLoggerName = loggerName;
}
}
1 change: 1 addition & 0 deletions packages/core/src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1089,6 +1089,7 @@ export interface IMidwayFramework<
useGuard(guard: CommonGuardUnion<CTX>): void;
runGuard(ctx: CTX, supplierClz: new (...args) => any, methodName: string): Promise<boolean>;
getNamespace(): string;
setFrameworkLoggerName(name: string): void;
}

export interface MidwayAppInfo {
Expand Down
12 changes: 11 additions & 1 deletion packages/core/src/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ import {
const debug = util.debuglog('midway:debug');

let stepIdx = 1;
let projectIdx = 1;
function printStepDebugInfo(stepInfo: string) {
debug(`\n\nStep ${stepIdx++}: ${stepInfo}\n`);
debug(`\n\nProject ${projectIdx} - Step ${stepIdx++}: ${stepInfo}\n`);
}

/**
Expand Down Expand Up @@ -139,24 +140,33 @@ export async function initializeGlobalApplicationContext(
export async function destroyGlobalApplicationContext(
applicationContext: IMidwayGlobalContainer
) {
printStepDebugInfo('Ready to destroy applicationContext');
const loggerService = await applicationContext.getAsync(MidwayLoggerService);
const loggerFactory = loggerService.getCurrentLoggerFactory();

printStepDebugInfo('Stopping lifecycle');
// stop lifecycle
const lifecycleService = await applicationContext.getAsync(
MidwayLifeCycleService
);
await lifecycleService.stop();

printStepDebugInfo('Stopping applicationContext');
// stop container
await applicationContext.stop();

printStepDebugInfo('Closing loggerFactory');
loggerFactory.close();

printStepDebugInfo('Cleaning performance manager');
MidwayPerformanceManager.cleanAll();

global['MIDWAY_APPLICATION_CONTEXT'] = undefined;
global['MIDWAY_MAIN_FRAMEWORK'] = undefined;

// reset counter
stepIdx = 1;
projectIdx++;
}

/**
Expand Down
15 changes: 7 additions & 8 deletions packages/core/test/baseFramework.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -833,15 +833,14 @@ describe('/test/baseFramework.test.ts', () => {
appDir,
'src'
), {
custom: {
contextLoggerApplyLogger: 'customFrameworkLogger',
contextLoggerFormat: info => {
return `[custom ctx] ${info.message}`;
},
},
custom: {},
midwayLogger: {
clients: {
customFrameworkLogger: {},
customFrameworkLogger: {
contextFormat: info => {
return `[custom ctx] ${info.message}`;
},
},
customLogger: {
format: info => {
return `[new custom] ${info.message}`;
Expand All @@ -860,7 +859,7 @@ describe('/test/baseFramework.test.ts', () => {
const mainFramework = midwayFrameworkService.getMainFramework();
const ctx = mainFramework.getApplication().createAnonymousContext();
expect(ctx.logger.info('hello world')).toEqual('[custom ctx] hello world');
expect(ctx.getLogger('appLogger').info('hello world')).toEqual('[custom ctx] hello world');
expect(ctx.getLogger('customFrameworkLogger').info('hello world')).toEqual('[custom ctx] hello world');
expect(ctx.getLogger('customLogger').info('hello world')).toEqual('[new custom ctx] hello world');
expect(mainFramework.getLogger('customLogger').info('hello world')).toEqual('[new custom] hello world');
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { BaseFramework, Framework, IMidwayBootstrapOptions } from '../../../../s

@Framework()
export class CustomFramework extends BaseFramework<any, any, any> {
frameworkLoggerName = 'customFrameworkLogger';
async applicationInitialize(options: IMidwayBootstrapOptions) {
this.app = {};
}
Expand All @@ -11,7 +12,7 @@ export class CustomFramework extends BaseFramework<any, any, any> {
}

run(): Promise<void> {
this.app.getCoreLogger().info('run custom framework');
this.logger.info('run custom framework');
return Promise.resolve(undefined);
}
}
1 change: 0 additions & 1 deletion packages/cron/src/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { JobNameOrClz } from './interface';
default: {
cron: {
defaultCronJobOptions: {},
contextLoggerApplyLogger: 'cronLogger',
},
midwayLogger: {
clients: {
Expand Down
1 change: 1 addition & 0 deletions packages/cron/src/framework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { CRON_JOB_KEY } from './constants';
export class CronFramework extends BaseFramework<Application, Context, any> {
private defaultCronJobConfig: CronOptions;
private jobs: Map<string, CronJob> = new Map();
protected frameworkLoggerName = 'cronLogger';

async applicationInitialize(options: IMidwayBootstrapOptions) {
this.app = {} as any;
Expand Down
7 changes: 7 additions & 0 deletions packages/grpc/src/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ import { GRPCClients } from './comsumer/clients';
default: {
grpc: {},
grpcServer: {},
midwayLogger: {
clients: {
grpcLogger: {
fileLogName: 'midway-grpc.log',
},
},
},
},
},
],
Expand Down
6 changes: 1 addition & 5 deletions packages/grpc/src/provider/framework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
ServerUnaryCall,
} from '@grpc/grpc-js';
import {
Config,
Framework,
GRPCMetadata,
GrpcStreamTypeEnum,
Expand Down Expand Up @@ -40,9 +39,7 @@ export class MidwayGRPCFramework extends BaseFramework<
> {
public app: IMidwayGRPCApplication;
private server: Server;

@Config()
providerConfig;
protected frameworkLoggerName = 'grpcLogger';

configure() {
return this.configService.getConfiguration('grpcServer');
Expand Down Expand Up @@ -231,7 +228,6 @@ export class MidwayGRPCFramework extends BaseFramework<
reject(err);
}

this.server.start();
this.logger.info(`Server port = ${bindPort} start success`);
resolve();
}
Expand Down
4 changes: 1 addition & 3 deletions packages/kafka/src/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import { Configuration } from '@midwayjs/core';
importConfigs: [
{
default: {
kafka: {
contextLoggerApplyLogger: 'kafkaLogger',
},
kafka: {},
midwayLogger: {
clients: {
kafkaLogger: {
Expand Down
Loading

0 comments on commit 9632927

Please sign in to comment.