Skip to content

Commit

Permalink
feat: support v3 logger (#3328)
Browse files Browse the repository at this point in the history
* feat: support v3 logger

* feat: support alias name in logger service

* chore: use logger v3

* chore: use logger v3 beta

* fix: typings

* fix: lint

* chore: upgrade to beta19

* fix: web logger

* fix: web case

* fix: build

* fix: cron logger case

* fix: logger api

* chore: update logger to 3.0.0 release

* docs: update logger document

* chore: update logger version
  • Loading branch information
czy88840616 authored Nov 13, 2023
1 parent 56920d4 commit a4586da
Show file tree
Hide file tree
Showing 47 changed files with 2,956 additions and 908 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,4 @@ docs-api
site/changelog
.changelog
**/test/*.txt
.audit
1 change: 0 additions & 1 deletion packages-legacy/serverless-worker-starter/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
"@midwayjs/core": "^3.12.3",
"@midwayjs/jest-environment-service-worker": "0.1.3",
"@midwayjs/jsdom-service-worker": "0.1.3",
"@midwayjs/logger": "^2.15.0",
"@midwayjs/runtime-mock": "^3.7.0"
},
"engines": {
Expand Down
1 change: 0 additions & 1 deletion packages-legacy/task/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
"devDependencies": {
"@midwayjs/core": "^3.12.3",
"@midwayjs/koa": "^3.12.10",
"@midwayjs/logger": "^2.15.0",
"@midwayjs/mock": "^3.12.10",
"@types/bull": "3.15.9",
"@types/cron": "2.0.1"
Expand Down
2 changes: 1 addition & 1 deletion packages/bootstrap/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
},
"devDependencies": {
"@midwayjs/core": "^3.12.3",
"@midwayjs/logger": "^2.15.0",
"@midwayjs/logger": "^3.0.0",
"request": "2.88.2",
"socket.io-client": "4.7.2"
},
Expand Down
27 changes: 18 additions & 9 deletions packages/bootstrap/src/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
isTypeScriptEnvironment,
} from '@midwayjs/core';
import { join } from 'path';
import { IMidwayLogger, MidwayBaseLogger } from '@midwayjs/logger';
import { ILogger, MidwayLoggerContainer, loggers } from '@midwayjs/logger';
import { createContextManager } from '@midwayjs/async-hooks-context-manager';
import {
ChildProcessEventBus,
Expand Down Expand Up @@ -59,6 +59,7 @@ export class BootstrapStarter {

this.applicationContext = await initializeGlobalApplicationContext({
asyncContextManager: createContextManager(),
loggerFactory: loggers,
...this.globalOptions,
});
return this.applicationContext;
Expand Down Expand Up @@ -105,8 +106,9 @@ export class BootstrapStarter {

export class Bootstrap {
protected static starter: BootstrapStarter;
protected static logger: IMidwayLogger;
protected static logger: ILogger;
protected static configured = false;
protected static bootstrapLoggerFactory = new MidwayLoggerContainer();

/**
* set global configuration for midway
Expand All @@ -115,16 +117,23 @@ export class Bootstrap {
static configure(configuration: IMidwayBootstrapOptions = {}) {
this.configured = true;
if (!this.logger && !configuration.logger) {
this.logger = new MidwayBaseLogger({
disableError: true,
disableFile: true,
});
this.logger = this.bootstrapLoggerFactory.createLogger('bootstrap', {
enableError: false,
enableFile: false,
enableConsole: true,
} as any);
if (configuration.logger === false) {
this.logger?.['disableConsole']();
if (this.logger['disableConsole']) {
// v2
this.logger['disableConsole']();
} else {
// v3
this.logger['level'] = 'none';
}
}
configuration.logger = this.logger;
} else {
this.logger = this.logger || (configuration.logger as IMidwayLogger);
this.logger = this.logger || (configuration.logger as ILogger);
}

// 处理三方框架内部依赖 process.cwd 来查找 node_modules 等问题
Expand Down Expand Up @@ -191,7 +200,7 @@ export class Bootstrap {
static reset() {
this.configured = false;
this.starter = null;
this.logger.close();
this.bootstrapLoggerFactory.close();
}

/**
Expand Down
5 changes: 5 additions & 0 deletions packages/bull/src/config/config.default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ export const midwayLogger = {
clients: {
bullLogger: {
fileLogName: 'midway-bull.log',
transports: {
file: {
fileLogName: 'midway-bull.log',
},
},
},
},
};
4 changes: 2 additions & 2 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@
"koa": "2.14.2",
"mm": "3.3.0",
"raw-body": "2.5.2",
"sinon": "15.2.0"
"sinon": "15.2.0",
"@midwayjs/logger": "^3.0.0"
},
"dependencies": {
"@midwayjs/glob": "^1.0.2",
"@midwayjs/logger": "^2.15.0",
"class-transformer": "0.5.1",
"picomatch": "2.3.1",
"reflect-metadata": "0.1.13"
Expand Down
22 changes: 8 additions & 14 deletions packages/core/src/baseFramework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,15 @@ import {
CommonFilterUnion,
MiddlewareRespond,
CommonGuardUnion,
ILogger,
MidwayLoggerOptions,
} from './interface';
import {
REQUEST_CTX_LOGGER_CACHE_KEY,
ASYNC_CONTEXT_KEY,
ASYNC_CONTEXT_MANAGER_KEY,
} from './constants';
import { Inject, Destroy, Init } from './decorator';
import {
ILogger,
LoggerOptions,
IMidwayLogger,
LoggerContextFormat,
} from '@midwayjs/logger';
import { MidwayRequestContainer } from './context/requestContainer';
import { MidwayEnvironmentService } from './service/environmentService';
import { MidwayConfigService } from './service/configService';
Expand Down Expand Up @@ -55,7 +51,7 @@ export abstract class BaseFramework<
protected appLogger: ILogger;
protected defaultContext = {};
protected contextLoggerApplyLogger: string;
protected contextLoggerFormat: LoggerContextFormat;
protected contextLoggerFormat: any;
protected middlewareManager = this.createMiddlewareManager();
protected filterManager = this.createFilterManager();
protected guardManager = this.createGuardManager();
Expand Down Expand Up @@ -157,9 +153,7 @@ export abstract class BaseFramework<
public abstract run(): Promise<void>;

protected createContextLogger(ctx: CTX, name?: string): ILogger {
const appLogger = this.getLogger(
name ?? this.contextLoggerApplyLogger
) as IMidwayLogger;
const appLogger = this.getLogger(name ?? this.contextLoggerApplyLogger);
if (name) {
let ctxLoggerCache = ctx.getAttr(REQUEST_CTX_LOGGER_CACHE_KEY) as Map<
string,
Expand All @@ -180,7 +174,7 @@ export abstract class BaseFramework<
}

// create new context logger
const ctxLogger = appLogger.createContextLogger<CTX>(ctx, {
const ctxLogger = this.loggerService.createContextLogger(ctx, appLogger, {
contextFormat: this.contextLoggerFormat,
});
ctxLoggerCache.set(name, ctxLogger);
Expand All @@ -190,7 +184,7 @@ export abstract class BaseFramework<
if (ctx['_logger']) {
return ctx['_logger'];
}
ctx['_logger'] = appLogger.createContextLogger<CTX>(ctx, {
ctx['_logger'] = this.loggerService.createContextLogger(ctx, appLogger, {
contextFormat: this.contextLoggerFormat,
});
return ctx['_logger'];
Expand Down Expand Up @@ -254,7 +248,7 @@ export abstract class BaseFramework<
return this.getLogger(name);
},

createLogger: (name: string, options: LoggerOptions = {}) => {
createLogger: (name: string, options: MidwayLoggerOptions = {}) => {
return this.createLogger(name, options);
},

Expand Down Expand Up @@ -448,7 +442,7 @@ export abstract class BaseFramework<
return this.logger;
}

public createLogger(name: string, option: LoggerOptions = {}) {
public createLogger(name: string, option: MidwayLoggerOptions = {}) {
return this.loggerService.createLogger(name, option);
}

Expand Down
46 changes: 45 additions & 1 deletion packages/core/src/common/loggerFactory.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,52 @@
import { ILogger } from '../interface';
import { ILogger, MidwayAppInfo } from '../interface';

export abstract class LoggerFactory<Logger extends ILogger, LoggerOptions> {
abstract createLogger(name: string, options: LoggerOptions): Logger;
abstract getLogger(loggerName: string): Logger;
abstract close(loggerName?: string);
abstract removeLogger(loggerName: string);
abstract getDefaultMidwayLoggerConfig(appInfo: MidwayAppInfo): {
midwayLogger: {
default?: LoggerOptions;
clients?: {
[loggerName: string]: LoggerOptions;
};
};
};
abstract createContextLogger(
ctx: any,
appLogger: ILogger,
contextOptions?: any
): ILogger;
}

export class DefaultConsoleLoggerFactory
implements LoggerFactory<ILogger, any>
{
createLogger(name: string, options: any): ILogger {
return console;
}
getLogger(loggerName: string): ILogger {
return console;
}
close(loggerName?: string) {}
removeLogger(loggerName: string) {}

getDefaultMidwayLoggerConfig(): {
midwayLogger: { default?: any; clients?: { [p: string]: any } };
} {
return {
midwayLogger: {
default: {},
clients: {
coreLogger: {},
appLogger: {},
},
},
};
}

createContextLogger(ctx: any, appLogger: ILogger): ILogger {
return appLogger;
}
}
8 changes: 0 additions & 8 deletions packages/core/src/config/config.default.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import type { MidwayAppInfo, MidwayCoreDefaultConfig } from '../interface';
import { getCurrentEnvironment, isDevelopmentEnvironment } from '../util/';
import { join } from 'path';
import { MIDWAY_LOGGER_WRITEABLE_DIR } from '../constants';

export default (appInfo: MidwayAppInfo): MidwayCoreDefaultConfig => {
const isDevelopment = isDevelopmentEnvironment(getCurrentEnvironment());
const logRoot = process.env[MIDWAY_LOGGER_WRITEABLE_DIR] ?? appInfo.root;
return {
core: {
healthCheckTimeout: 1000,
Expand All @@ -15,18 +12,13 @@ export default (appInfo: MidwayAppInfo): MidwayCoreDefaultConfig => {
},
midwayLogger: {
default: {
dir: join(logRoot, 'logs', appInfo.name),
level: 'info',
consoleLevel: isDevelopment ? 'info' : 'warn',
auditFileDir: '.audit',
},
clients: {
coreLogger: {
level: isDevelopment ? 'info' : 'warn',
fileLogName: 'midway-core.log',
},
appLogger: {
fileLogName: 'midway-app.log',
aliasName: 'logger',
},
},
Expand Down
2 changes: 0 additions & 2 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,5 +81,3 @@ export { Types } from './util/types';
export { PathFileUtil } from './util/pathFileUtil';
export { FileUtils } from './util/fs';
export { FORMAT } from './util/format';

export type { ILogger, IMidwayLogger } from '@midwayjs/logger';
52 changes: 45 additions & 7 deletions packages/core/src/interface.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { LoggerOptions, LoggerContextFormat } from '@midwayjs/logger';
import * as EventEmitter from 'events';
import type { AsyncContextManager } from './common/asyncContextManager';
import type { LoggerFactory } from './common/loggerFactory';
Expand Down Expand Up @@ -399,17 +398,56 @@ export interface ParamDecoratorOptions {
pipes?: PipeUnionTransform<any, any>[];
}

/**
* Logger Options for midway, you can merge this interface in package
* @example
* ```typescript
*
* import { IMidwayLogger } from '@midwayjs/logger';
*
* declare module '@midwayjs/core/dist/interface' {
* interface ILogger extends IMidwayLogger {
* }
* }
*
* ```
*/
export interface ILogger {
info(msg: any, ...args: any[]): void;
debug(msg: any, ...args: any[]): void;
error(msg: any, ...args: any[]): void;
warn(msg: any, ...args: any[]): void;
}

/**
* @deprecated
*/
export type IMidwayLogger = ILogger;

/**
* Logger Options for midway, you can merge this interface in package
* @example
* ```typescript
*
* import { LoggerOptions } from '@midwayjs/logger';
*
* declare module '@midwayjs/core/dist/interface' {
* interface MidwayLoggerOptions extends LoggerOptions {
* logDir?: string;
* level?: string;
* }
* }
*
* ```
*/
export interface MidwayLoggerOptions {
lazyLoad?: boolean;
aliasName?: string;
[key: string]: any;
}

export interface MidwayCoreDefaultConfig {
midwayLogger?: ServiceFactoryConfigOption<LoggerOptions & {
lazyLoad?: boolean;
}>;
midwayLogger?: ServiceFactoryConfigOption<MidwayLoggerOptions>;
debug?: {
recordConfigMergeOrder?: boolean;
};
Expand Down Expand Up @@ -961,7 +999,7 @@ export interface IMidwayBaseApplication<CTX extends IMidwayContext> {
* @param name
* @param options
*/
createLogger(name: string, options: LoggerOptions): ILogger;
createLogger(name: string, options: MidwayLoggerOptions): ILogger;

/**
* Get project name, just package.json name
Expand Down Expand Up @@ -1064,7 +1102,7 @@ export interface IConfigurationOptions {
logger?: ILogger;
appLogger?: ILogger;
contextLoggerApplyLogger?: string;
contextLoggerFormat?: LoggerContextFormat;
contextLoggerFormat?: any;
}

export interface IMidwayFramework<
Expand All @@ -1090,7 +1128,7 @@ export interface IMidwayFramework<
getBaseDir(): string;
getLogger(name?: string): ILogger;
getCoreLogger(): ILogger;
createLogger(name: string, options: LoggerOptions): ILogger;
createLogger(name: string, options: MidwayLoggerOptions): ILogger;
getProjectName(): string;
useMiddleware(Middleware: CommonMiddlewareUnion<CTX, ResOrNext, Next>): void;
getMiddleware(): IMiddlewareManager<CTX, ResOrNext, Next>;
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/service/configService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,4 +263,8 @@ export class MidwayConfigService implements IConfigService {
}
return config;
}

public getAppInfo() {
return this.appInfo;
}
}
Loading

0 comments on commit a4586da

Please sign in to comment.