Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: feat: first implement logger #143

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -762,7 +762,7 @@ import { EggObjectFactory } from '@eggjs/tegg';
export class HelloService {
@Inject()
private readonly eggObjectFactory: EggObjectFactory;

async hello(): Promise<string> {
const helloImpl = await this.eggObjectFactory.getEggObject(AbstractHello, HelloType.BAR);
return helloImpl.hello();
Expand Down
1 change: 1 addition & 0 deletions core/logger/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Change Log
3 changes: 3 additions & 0 deletions core/logger/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# `@eggjs/logger-decorator`

# Usage
3 changes: 3 additions & 0 deletions core/logger/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './src/decorator/LoggerDecorator';
export * from './src/logger/BaseLogger';
export * from './src/logger/LoggerLevel';
54 changes: 54 additions & 0 deletions core/logger/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"name": "@eggjs/logger",
"version": "3.14.3",
"description": "tegg logger",
"keywords": [
"tegg",
"logger",
"typescript",
"egg"
],
"author": "popomore <sakura9515@gmail.com>",
"homepage": "https://github.com/eggjs/tegg",
"repository": {
"type": "git",
"url": "git@github.com:eggjs/tegg.git",
"directory": "core/logger"
},
"dependencies": {
"@eggjs/core-decorator": "^3.14.3",
"@eggjs/tegg-common-util": "^3.14.3",
"@eggjs/tegg-metadata": "^3.14.3",
"is-type-of": "^2.0.1"
},
"scripts": {
"test": "cross-env NODE_ENV=test NODE_OPTIONS='--no-deprecation' mocha",
"clean": "tsc -b --clean",
"tsc": "npm run clean && tsc -p ./tsconfig.json",
"tsc:pub": "npm run clean && tsc -p ./tsconfig.pub.json",
"prepublishOnly": "npm run tsc:pub"
},
"publishConfig": {
"access": "public"
},
"engines": {
"node": ">=14.0.0"
},
"license": "MIT",
"main": "dist/index.js",
"files": [
"dist/**/*.js",
"dist/**/*.d.ts"
],
"bugs": {
"url": "https://github.com/eggjs/tegg/issues"
},
"devDependencies": {
"@types/mocha": "^10.0.1",
"@types/node": "^20.2.4",
"cross-env": "^7.0.3",
"mocha": "^10.2.0",
"ts-node": "^10.9.1",
"typescript": "^5.0.4"
}
}
23 changes: 23 additions & 0 deletions core/logger/src/decorator/LoggerDecorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { AccessLevel, EggProtoImplClass, PrototypeUtil, SingletonProto } from '@eggjs/core-decorator';
import { StackUtil } from '@eggjs/tegg-common-util';
import { LoggerMetaUtil } from '../logger/LoggerUtil';
import { ILogger } from '../type/ILogger';
import { LoggerDecoratorParams } from '../type/LoggerDecoratorParams';

/**
* Logger Decorator
*
* Define the object is Logger object
*/
export function LoggerDecorator(params?: LoggerDecoratorParams) {
return function(constructor: EggProtoImplClass<ILogger>) {
LoggerMetaUtil.setLoggerFlag(constructor);
LoggerMetaUtil.setLoggerMeta(constructor, params);
const func = SingletonProto({
accessLevel: AccessLevel.PRIVATE,
name: params?.name,
});
func(constructor);
PrototypeUtil.setFilePath(constructor, StackUtil.getCalleeFromStack(false, 5));
};
}
35 changes: 35 additions & 0 deletions core/logger/src/logger/BaseLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Logger } from 'egg-logger';
import { LoggerFactory } from './LoggerFactory';
import { ILogger } from '../type/ILogger';
import { LoggerMetaUtil } from './LoggerUtil';

export class BaseLogger implements ILogger {

#logger: Logger;

constructor() {
const options = LoggerMetaUtil.getLoggerMeta(this.constructor as any);
this.#logger = LoggerFactory.getOrCreateLogger(options);
}

public debug(message: any, ...args: any[]): void {
this.#logger.debug(message, ...args);
}

public error(message: any, ...args: any[]): void {
this.#logger.error(message, ...args);
}

public info(message: any, ...args: any[]): void {
this.#logger.error(message, ...args);
}

public warn(message: any, ...args: any[]): void {
this.#logger.warn(message, ...args);
}

public write(message: any): void {
this.#logger.write(message);
}

}
43 changes: 43 additions & 0 deletions core/logger/src/logger/LoggerFactory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Logger } from 'egg-logger';
import is from 'is-type-of';
import { LoggerDecoratorParams } from '../type/LoggerDecoratorParams';
import { LoggerLevel } from './LoggerLevel';

const defaultOptions: Partial<LoggerDecoratorParams> = {
level: LoggerLevel.INFO,
};

export class LoggerFactory {

static #loggerMap = new Map<string, Logger>();

static getOrCreateLogger(options?: LoggerDecoratorParams): Logger {
const opt = {
...defaultOptions,
...options,
};

if (is.nullable(opt.file)) throw new Error('options.file is required');
if (is.nullable(opt.name)) throw new Error('options.name is required');

const name = opt.name;
let logger = this.#loggerMap.get(name);
if (logger) return logger;

logger = new Logger({
level: opt.level,
file: opt.file,
});
this.#loggerMap.set(name, logger);
return logger;
}

static getLogger(name: string): Logger | undefined {
return this.#loggerMap.get(name);
}

// static destroyAll() {

// }

}
7 changes: 7 additions & 0 deletions core/logger/src/logger/LoggerLevel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export enum LoggerLevel {
DEBUG = 'DEBUG',
INFO = 'INFO',
WARN = 'WARN',
ERROR = 'ERROR',
NONE = 'NONE',
}
27 changes: 27 additions & 0 deletions core/logger/src/logger/LoggerUtil.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { EggProtoImplClass, MetadataUtil } from '@eggjs/core-decorator';
import { LoggerDecoratorParams } from '../type/LoggerDecoratorParams';
import { ILogger } from '../type/ILogger';
import is from 'is-type-of';

export const LOGGER_OPTIONS = Symbol.for('EggPrototype#loggerOptions');
export const IS_LOGGER = Symbol.for('EggPrototype#isLogger');

export class LoggerMetaUtil {
static setLoggerMeta(clazz: EggProtoImplClass<ILogger>, params?: LoggerDecoratorParams) {
MetadataUtil.defineMetaData(LOGGER_OPTIONS, params, clazz);
}

static getLoggerMeta(clazz: EggProtoImplClass<ILogger>): LoggerDecoratorParams | undefined {
return MetadataUtil.getOwnMetaData(LOGGER_OPTIONS, clazz);
}

static setLoggerFlag(clazz: EggProtoImplClass<ILogger>) {
MetadataUtil.defineMetaData(IS_LOGGER, true, clazz);
}

static getLoggerFlag(clazz: EggProtoImplClass<ILogger>): boolean {
const result = MetadataUtil.getOwnMetaData<boolean>(IS_LOGGER, clazz);
return is.undefined(result) ? false : result;
}

}
10 changes: 10 additions & 0 deletions core/logger/src/module/Logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { LoggerDecorator } from '../decorator/LoggerDecorator';
import { BaseLogger } from '../logger/BaseLogger';

@LoggerDecorator({
name: 'logger',
transports: [
new (require('egg-logger').EggConsoleTransport)({
],
})
export class Logger extends BaseLogger {}
7 changes: 7 additions & 0 deletions core/logger/src/type/ILogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export interface ILogger {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ILogger 是不是单独发一个 npm 包?像 layotto js-sdk 其实不感知 tegg 的存在的。

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

那是不是把 zlogger 这个库改造下,把 egg-logger 的一些实现放过去

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

最好就是纯 interface 定义,这样依赖都可以不添加。https://github.com/layotto/js-sdk/blob/main/src/client/Client.ts#L79

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

对啊,正常还是可以依赖一个 logger 的,现在只是没有承载。

error(message: any, ...args: any[]): void;
warn(message: any, ...args: any[]): void;
info(message: any, ...args: any[]): void;
debug(message: any, ...args: any[]): void;
write(message: any, ...args: any[]): void;
}
17 changes: 17 additions & 0 deletions core/logger/src/type/LoggerDecoratorParams.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { LoggerLevel } from '../logger/LoggerLevel';

export interface LoggerDecoratorParams {
name?: string;
level?: LoggerLevel;
file: string;
// encoding?: string;
// consoleLevel?: LoggerLevel;
// formatter?: (meta?: LoggerMeta) => string;
// paddingMessageFormatter?: (ctx: object) => string;
// jsonFile?: string;
// outputJSON?: boolean;
// buffer?: boolean;
// dateISOFormat?: boolean;
// eol?: string;
// concentrateError?: 'duplicate' | 'redirect' | 'ignore';
}
43 changes: 43 additions & 0 deletions core/logger/test/Logger.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import path from 'path';
import { LoadUnitInstance, LoadUnitInstanceFactory } from '@eggjs/tegg-runtime';
import { LoadUnitFactory } from '@eggjs/tegg-metadata';
import { EggTestContext } from '../../test-util';
import { HelloService } from './fixtures/modules/dynamic-inject-module/HelloService';
import { CoreTestHelper } from '../../test-util/CoreTestHelper';
import assert from 'assert';
import { TraceLogger } from './fixtures/logger/TraceLogger';

describe('test/Logger.test.ts', () => {


let modules: Array<LoadUnitInstance>;
beforeEach(async () => {
modules = await CoreTestHelper.prepareModules([
path.join(__dirname, '..'),
path.join(__dirname, 'fixtures/logger'),
]);
});

afterEach(async () => {
for (const module of modules) {
await LoadUnitFactory.destroyLoadUnit(module.loadUnit);
await LoadUnitInstanceFactory.destroyLoadUnitInstance(module);
}
});

describe('Pointcut', () => {
it('should work', async () => {
const traceLogger = await CoreTestHelper.getObject(TraceLogger);
traceLogger.info('info %s', );
});
});

// describe('Logger Define', () => {

// });

// describe('Logger Manager', () => {

// });

});
6 changes: 6 additions & 0 deletions core/logger/test/fixtures/logger/TraceLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { BaseLogger, LoggerDecorator } from '../../..';

@LoggerDecorator({
file: 'trace.log',
})
export class TraceLogger extends BaseLogger{}
12 changes: 12 additions & 0 deletions core/logger/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "dist",
"baseUrl": "./"
},
"exclude": [
"dist",
"node_modules",
"test"
]
}
12 changes: 12 additions & 0 deletions core/logger/tsconfig.pub.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "dist",
"baseUrl": "./"
},
"exclude": [
"dist",
"node_modules",
"test"
]
}