Skip to content

Commit

Permalink
feat: add logger.write method (#844)
Browse files Browse the repository at this point in the history
* feat: add logger.write method

* fix: lint
  • Loading branch information
czy88840616 committed Feb 7, 2021
1 parent 7b27145 commit 0051d07
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 8 deletions.
5 changes: 5 additions & 0 deletions packages/logger/src/format.ts
Expand Up @@ -16,6 +16,10 @@ export const displayCommonMessage = format(
info.pid = process.pid;
}

if (!info.ignoreFormat) {
info.ignoreFormat = false;
}

if (!info.LEVEL) {
info.LEVEL = info.level.toUpperCase();
}
Expand All @@ -38,6 +42,7 @@ export const displayCommonMessage = format(
pid: info.pid,
LEVEL: info.LEVEL,
defaultLabel: info.defaultLabel,
ignoreFormat: info.ignoreFormat,
},
opts.defaultMeta || opts.target?.getDefaultMeta() || {}
);
Expand Down
1 change: 1 addition & 0 deletions packages/logger/src/interface.ts
Expand Up @@ -21,6 +21,7 @@ export interface IMidwayLogger extends ILogger {
updateDefaultMeta(defaultMeta: object): void;
getDefaultLabel(): string;
getDefaultMeta(): Record<string, unknown>;
write(...args): boolean;
}

export type LoggerLevel = 'silly' | 'debug' | 'info' | 'warn' | 'error';
Expand Down
51 changes: 44 additions & 7 deletions packages/logger/src/logger.ts
Expand Up @@ -15,6 +15,16 @@ const isWindows = os.platform() === 'win32';

export const EmptyLogger: Logger = createLogger().constructor as Logger;

const midwayLogLevels = {
all: 0,
error: 1,
warn: 2,
info: 3,
verbose: 4,
debug: 5,
silly: 6,
};

/**
* base logger with console transport and file transport
*/
Expand All @@ -27,7 +37,11 @@ export class MidwayBaseLogger extends EmptyLogger implements IMidwayLogger {
defaultMetadata = {};

constructor(options: LoggerOptions = {}) {
super(options);
super(
Object.assign(options, {
levels: midwayLogLevels,
})
);
this.exitOnError = false;
if (isWindows) {
options.disableErrorSymlink = true;
Expand Down Expand Up @@ -62,7 +76,13 @@ export class MidwayBaseLogger extends EmptyLogger implements IMidwayLogger {
format.colorize({
all: true,
colors: {
all: 'reset',
error: 'red',
warn: 'yellow',
info: 'reset',
verbose: 'reset',
debug: 'blue',
silly: 'reset',
},
})
),
Expand Down Expand Up @@ -166,6 +186,12 @@ export class MidwayBaseLogger extends EmptyLogger implements IMidwayLogger {
}

getDefaultLoggerConfigure() {
const printInfo = this.loggerOptions.printFormat
? this.loggerOptions.printFormat
: info => {
return `${info.timestamp} ${info.LEVEL} ${info.pid} ${info.labelText}${info.message}`;
};

return {
format: format.combine(
displayCommonMessage({
Expand All @@ -176,12 +202,12 @@ export class MidwayBaseLogger extends EmptyLogger implements IMidwayLogger {
format: 'YYYY-MM-DD HH:mm:ss,SSS',
}),
format.splat(),
format.printf(
this.loggerOptions.printFormat
? this.loggerOptions.printFormat
: info =>
`${info.timestamp} ${info.LEVEL} ${info.pid} ${info.labelText}${info.message}`
)
format.printf(info => {
if (info.ignoreFormat) {
return info.message;
}
return printInfo(info);
})
),
};
}
Expand All @@ -193,6 +219,17 @@ export class MidwayBaseLogger extends EmptyLogger implements IMidwayLogger {
getDefaultMeta(): Record<string, unknown> {
return this.defaultMetadata;
}

write(...args): any {
if (
(args.length === 1 && typeof args[0] !== 'object') ||
!args[0]['level']
) {
return super.log.apply(this, ['all', ...args, { ignoreFormat: true }]);
} else {
return super.write.apply(this, args);
}
}
}

/**
Expand Down
18 changes: 18 additions & 0 deletions packages/logger/test/index.test.ts
Expand Up @@ -510,4 +510,22 @@ describe('/test/index.test.ts', () => {
await removeFileOrDir(logsDir);
});

it('should use write method to file', async () => {
clearAllLoggers();
const logsDir = join(__dirname, 'logs');
await removeFileOrDir(logsDir);
const logger = createLogger<IMidwayLogger>('logger', {
dir: logsDir,
disableError: true,
});
logger.write('hello world');
const buffer = Buffer.from('hello world', 'utf-8');
logger.write(buffer);

await sleep();
expect(matchContentTimes(join(logsDir, 'midway-core.log'), process.pid.toString())).toEqual(0);
expect(matchContentTimes(join(logsDir, 'midway-core.log'), 'hello world')).toEqual(2);
await removeFileOrDir(logsDir);
});

});
2 changes: 1 addition & 1 deletion packages/logger/test/util.ts
Expand Up @@ -45,7 +45,7 @@ export const matchContentTimes = (p: string, matchString: string | RegExp) => {
}

if (typeof matchString === 'string') {
matchString = new RegExp(matchString);
matchString = new RegExp(matchString, 'g');
}

const result = content.match(matchString) || [];
Expand Down

0 comments on commit 0051d07

Please sign in to comment.