Skip to content

Commit 67a64c8

Browse files
realyuyananmapleeit
authored andcommitted
feat: support logging with winston
1 parent 3a58392 commit 67a64c8

File tree

10 files changed

+103
-5
lines changed

10 files changed

+103
-5
lines changed

README.md

+25
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,31 @@ module.exports = {
127127
| -- | -- | -- | -- |
128128
| plugins || `new Plugin[]` | 插件列表 |
129129

130+
<h2 align="center">winston</h2>
131+
132+
### winston 是什么?
133+
134+
`winston` 是一个通用且轻量的日志包。`winston` 支持多个日志通道,并且可以分别定义日志优先级。除了内置的三个日志传输通道[`Console``File``HTTP`](https://github.com/winstonjs/winston#common-transport-options),在 Winston 项目外部还会维护一些[传输模块](https://github.com/winstonjs)。查看 `winston` [官方文档](https://github.com/winstonjs/winston)
135+
136+
TSW 2.0 支持使用 `winston` 传输通道记录日志信息,用户在配置文件中可以添加 `winston.transports` 实例,日志会落到对应配置中。
137+
138+
### 一个简单的示例
139+
140+
使用 `winston` 记录 `error` 级别 以及 `debug` 级别以下的日志信息到对应文件中,当前 `config` 文件配置如下:
141+
142+
```js
143+
module.exports = {
144+
winston: [
145+
new winston.transports.File({ filename: 'error.log', level: 'error'}),
146+
new winston.transports.File({ filename: 'debug.log', level: 'debug'})
147+
]
148+
}
149+
```
150+
151+
**日志记录**
152+
153+
![log](./static/images/winston-log.png)
154+
130155
<h2 align="center">License</h2>
131156

132157
Tencent Server Web 的开源协议为 MIT, 详情参见 [LICENSE](https://github.com/Tencent/TSW/blob/master/LICENSE)

examples/koa/package.json

+5-3
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@
77
"main": "index.js",
88
"license": "MIT",
99
"dependencies": {
10-
"@tswjs/open-platform-plugin": "^0.0.7",
10+
"@tswjs/open-platform-plugin": "0.0.7",
1111
"@tswjs/tsw": "^2.0.0-alpha",
12-
"axios": "^0.19.0",
13-
"koa": "^2.11.0"
12+
"axios": "^0.19.2",
13+
"koa": "^2.11.0",
14+
"winston": "^3.2.1",
15+
"winston-transport": "^4.3.0"
1416
}
1517
}

examples/koa/tswconfig.js

+5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
const winston = require("winston");
12
const OpenPlatformPlugin = require("@tswjs/open-platform-plugin");
23

34
module.exports = {
@@ -23,5 +24,9 @@ module.exports = {
2324
};
2425
}
2526
})
27+
],
28+
winstonTransports: [
29+
new winston.transports.File({ filename: 'error.log', level: 'error'}),
30+
new winston.transports.File({ filename: 'debug.log', level: 'debug'})
2631
]
2732
};

lib/core/__test__/winston.test.ts

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { winstonHack } from "../winston";
2+
import logger from "../../core/logger/index";
3+
4+
describe("test winstonHack env", () => {
5+
test("test logger's winstonLogger when it hasn't hacked", () => {
6+
expect(logger.winstonLogger).toBe(undefined);
7+
});
8+
9+
global.tswConfig.winstonTransports = undefined;
10+
winstonHack();
11+
test("test winstonHack while config without winstonTransports ", () => {
12+
expect(logger.winstonLogger.log).toBe(undefined);
13+
});
14+
});

lib/core/logger/index.ts

+28
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import isLinux from "../util/isLinux";
1515
import isInspect from "../util/isInspect";
1616
import getCallInfo from "./callInfo";
1717
import { Stream } from "stream";
18+
import { config as winstonConfig, Logger as WinstonLogger } from "winston";
1819

1920
enum LOG_LEVEL {
2021
"DEBUG" = 10,
@@ -32,9 +33,13 @@ enum LOG_COLOR {
3233

3334
type LogLevelStrings = keyof typeof LOG_LEVEL;
3435

36+
type WinstonLogLevel = keyof typeof winstonConfig.syslog.levels;
37+
3538
export class Logger {
3639
public logLevel: number
3740

41+
public winstonLogger: WinstonLogger
42+
3843
public setLogLevel(level: LogLevelStrings): number {
3944
this.logLevel = LOG_LEVEL[level];
4045
return this.logLevel;
@@ -103,6 +108,11 @@ export class Logger {
103108
// Store log
104109
Logger.fillBuffer(type, logStr);
105110

111+
if (this.winstonLogger) {
112+
const winstonLogType = Logger.getWinstonType(type);
113+
this.winstonLogger.log(`${winstonLogType}`, logStr);
114+
}
115+
106116
if (isInspect()) {
107117
// When started with inspect, log will send to 2 places
108118
// 1. Local stdout
@@ -124,6 +134,24 @@ export class Logger {
124134
}
125135
}
126136

137+
/**
138+
* Convert TSW log level to winston log level
139+
* @param type Type of tsw log level
140+
*/
141+
private static getWinstonType(type: LogLevelStrings): WinstonLogLevel {
142+
const logType = type.toLowerCase();
143+
const winstonLogLevel = winstonConfig.syslog.levels;
144+
if (winstonLogLevel[logType]) {
145+
return logType;
146+
}
147+
148+
/**
149+
* Take the least important level from Winston syslog levels
150+
*/
151+
const levels = Object.keys(winstonLogLevel);
152+
return levels[levels.length - 1];
153+
}
154+
127155
/**
128156
* Format a string based on it's type(DEBUG/INFO/...)
129157
* @param str String need to be formatted

lib/core/winston.ts

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/* !
2+
* Tencent is pleased to support the open source community by making Tencent Server Web available.
3+
* Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
4+
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
5+
* http://opensource.org/licenses/MIT
6+
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
7+
*/
8+
9+
import * as winston from "winston";
10+
import * as Transports from "winston-transport";
11+
import logger from "./logger/index";
12+
13+
export const winstonHack = (): void => {
14+
const transports: Array<Transports> = global.tswConfig.winstonTransports;
15+
if (transports) {
16+
logger.winstonLogger = winston.createLogger({
17+
format: winston.format.simple(),
18+
transports
19+
});
20+
}
21+
};

lib/index.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { httpCreateServerHack } from "./core/runtime/create-server.hack";
44
import { dnsHack } from "./core/runtime/dns.hack";
55
import { requestHack } from "./core/runtime/capture/index";
66
import { eventBus } from "./core/bus";
7+
import { winstonHack } from "./core/winston";
78

89
export default async (
910
basePath: string,
@@ -12,7 +13,6 @@ export default async (
1213
): Promise<void> => {
1314
const configAbsolutePath = path.resolve(basePath, configPath);
1415
global.tswConfig = await import(configAbsolutePath);
15-
1616
// eslint-disable-next-line no-restricted-syntax
1717
for (const plugin of global.tswConfig.plugins) {
1818
// eslint-disable-next-line no-await-in-loop
@@ -26,6 +26,7 @@ export default async (
2626
dnsHack();
2727
consoleHack();
2828
requestHack();
29+
winstonHack();
2930

3031
await import(path.resolve(basePath, mainPath));
3132
};

package.json

+2
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@
6565
"ip": "^1.1.5",
6666
"lodash": "^4.17.15",
6767
"moment": "^2.24.0",
68+
"winston": "^3.2.1",
69+
"winston-transport": "^4.3.0",
6870
"yargs": "^15.0.2"
6971
}
7072
}

static/images/winston-log.png

1.03 MB
Loading

typings/type.d.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,10 @@ declare namespace NodeJS {
2323
interface Domain {
2424
currentContext?: any;
2525
}
26-
2726
interface Global {
2827
tswConfig: {
2928
plugins: any[];
29+
winstonTransports: any[];
3030
};
3131
}
3232
}

0 commit comments

Comments
 (0)