Skip to content

Commit

Permalink
fix: ctx get logger with custom logger (#3648)
Browse files Browse the repository at this point in the history
* fix: ctx get logger with custom logger

* fix: ctx get logger with custom logger
  • Loading branch information
czy88840616 committed Feb 17, 2024
1 parent 32f710b commit 4a9f039
Show file tree
Hide file tree
Showing 7 changed files with 177 additions and 13 deletions.
14 changes: 4 additions & 10 deletions packages/core/src/baseFramework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,8 @@ export abstract class BaseFramework<
public abstract run(): Promise<void>;

protected createContextLogger(ctx: CTX, name?: string): ILogger {
const appLogger = this.getLogger(name ?? this.contextLoggerApplyLogger);
if (name) {
if (name && name !== 'appLogger') {
const appLogger = this.getLogger(name);
let ctxLoggerCache = ctx.getAttr(REQUEST_CTX_LOGGER_CACHE_KEY) as Map<
string,
ILogger
Expand All @@ -163,23 +163,17 @@ export abstract class BaseFramework<
ctxLoggerCache = new Map();
ctx.setAttr(REQUEST_CTX_LOGGER_CACHE_KEY, ctxLoggerCache);
}

if (!name) {
name = 'appLogger';
}

// if logger exists
if (ctxLoggerCache.has(name)) {
return ctxLoggerCache.get(name);
}

// create new context logger
const ctxLogger = this.loggerService.createContextLogger(ctx, appLogger, {
contextFormat: this.contextLoggerFormat,
});
const ctxLogger = this.loggerService.createContextLogger(ctx, appLogger);
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'];
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/common/loggerFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export class DefaultConsoleLoggerFactory
};
}

createContextLogger(ctx: any, appLogger: ILogger): ILogger {
createContextLogger(ctx: any, appLogger: ILogger, contextOptions?): ILogger {
return appLogger;
}

Expand Down
121 changes: 120 additions & 1 deletion packages/core/test/baseFramework.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
ASYNC_CONTEXT_MANAGER_KEY,
APPLICATION_KEY,
MidwayFrameworkType,
Provide
Provide, IMidwayContainer, DefaultConsoleLoggerFactory, ILogger
} from '../src';
import { createFramework, createLightFramework } from './util';
import sinon = require('sinon');
Expand Down Expand Up @@ -742,4 +742,123 @@ describe('/test/baseFramework.test.ts', () => {
a.invokeD();
}).toThrow(/custom1 not found/);
});

describe('should create custom framework', () => {

let applicationContext: IMidwayContainer;

beforeAll(async () => {
class Logger {
constructor(protected options) {
if (!this.options.format) {
this.options.format = info => info.message;
}
}

info(msg) {
return this.options.format({
message: msg,
});
}
debug(msg) {
return this.options.format({
message: msg,
});
}
warn(msg) {
return this.options.format({
message: msg,
});
}
error(msg) {
return this.options.format({
message: msg,
});
}
}
class ContextLogger {
constructor(protected appLogger, protected options) {
this.options = {
...appLogger.options,
...options
}
}
info(msg) {
msg = this.options.contextFormat({
message: msg,
});
return msg;
}
debug(msg) {
msg = this.options.contextFormat({
message: msg,
});
return msg;
}
warn(msg) {
msg = this.options.contextFormat({
message: msg,
});
return msg;
}
error(msg) {
msg = this.options.contextFormat({
message: msg,
});
return msg;
}
}
class TestConsoleLoggerFactory extends DefaultConsoleLoggerFactory {
createLogger(name: string, options: any): ILogger {
const logger = new Logger(options);
this['instance'].set(name, logger);
return logger;
}
createContextLogger(ctx: any, appLogger: ILogger, options): ILogger {
return new ContextLogger(appLogger, options);
}
}

const loggerFactory = new TestConsoleLoggerFactory();

const appDir = path.join(
__dirname,
'./fixtures/base-app-custom-framework-logger'
);
applicationContext = await createFramework(path.join(
appDir,
'src'
), {
custom: {
contextLoggerApplyLogger: 'customFrameworkLogger',
contextLoggerFormat: info => {
return `[custom ctx] ${info.message}`;
},
},
midwayLogger: {
clients: {
customFrameworkLogger: {},
customLogger: {
format: info => {
return `[new custom] ${info.message}`;
},
contextFormat: info => {
return `[new custom ctx] ${info.message}`;
},
}
}
}
}, loggerFactory);
});

it('should test custom framework apply logger', async () => {
const midwayFrameworkService = applicationContext.get(MidwayFrameworkService);
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('customLogger').info('hello world')).toEqual('[new custom ctx] hello world');
expect(mainFramework.getLogger('customLogger').info('hello world')).toEqual('[new custom] hello world');
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"name": "ali-demo"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Configuration, App, Logger } from '../../../../src';
import { IMidwayApplication } from '../../../../src';
import { ILogger } from '@midwayjs/logger';

@Configuration({
importConfigs: {
midwayLogger: {
default: {
enableFile: false,
enableError: false,
},
clients: {
customLogger: {
enableConsole: true,
}
}
}
}
})
export class AutoConfiguration {

@App()
app: IMidwayApplication;

@Logger()
logger: ILogger;

async onReady() {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { BaseFramework, Framework, IMidwayBootstrapOptions } from '../../../../src';

@Framework()
export class CustomFramework extends BaseFramework<any, any, any> {
applicationInitialize(options: IMidwayBootstrapOptions) {
this.app = {};
}

configure(options: any) {
return this.configService.getConfiguration('custom');
}

run(): Promise<void> {
this.app.getCoreLogger().info('run custom framework');
return Promise.resolve(undefined);
}
}
3 changes: 2 additions & 1 deletion packages/core/test/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ export async function createLightFramework(baseDir: string = '', globalConfig: a
return container.getAsync(EmptyFramework as any);
}

export async function createFramework(baseDir: string = '', globalConfig: any = {}): Promise<IMidwayContainer> {
export async function createFramework(baseDir: string = '', globalConfig: any = {}, loggerFactory?): Promise<IMidwayContainer> {
const container = new MidwayContainer();
const bindModuleMap: WeakMap<any, boolean> = new WeakMap();
// 这里设置是因为在 midway 单测中会不断的复用装饰器元信息,又不能清理缓存,所以在这里做一些过滤
Expand Down Expand Up @@ -189,6 +189,7 @@ export async function createFramework(baseDir: string = '', globalConfig: any =
],
applicationContext: container,
globalConfig,
loggerFactory,
});
}

Expand Down

0 comments on commit 4a9f039

Please sign in to comment.