forked from xiangsx/gpt4free-ts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.ts
224 lines (199 loc) · 5.98 KB
/
log.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import path from 'path';
import winston, { Logger } from 'winston';
// @ts-ignore
import Transport from 'winston-transport';
import { Socket } from 'dgram';
import * as dgram from 'dgram';
import { format } from 'util';
import moment from 'moment';
import { Config } from './config';
import { ecsFields, ecsFormat } from '@elastic/ecs-winston-format';
import { colorLabel } from './index';
import { ChatRequest } from '../model/base';
import * as net from 'node:net';
let logger: Logger;
export const initLog = () => {
const logDir = path.join(process.cwd(), 'run/logs');
const transports: any[] = [];
if (process.env.LOG_CONSOLE !== '0') {
transports.push(
new winston.transports.Console({
format: winston.format.colorize(),
}),
);
}
if (process.env.LOG_FILE !== '0') {
transports.push(
// 写入所有日志记录到 `combined.log`
new winston.transports.File({
filename: path.join(logDir, 'combined.log'),
}),
// 写入所有级别为 error 的日志记录和以下到 `error.log`
new winston.transports.File({
filename: path.join(logDir, 'error.log'),
level: 'warn',
}),
);
}
if (process.env.LOG_ELK === '1') {
const port = +(process.env.LOG_ELK_PORT || 28777);
const host = process.env.LOG_ELK_HOST || '';
if (!host) {
throw new Error('LOG_ELK_HOST is required');
}
console.log(`init winston elk ${host} ${port}`);
transports.push(
new UDPTransport({
host,
port,
format: ecsFields(),
}),
);
}
winston.exceptions.handle(
new winston.transports.Console({
format: winston.format.colorize(),
}),
);
winston.exitOnError = false;
logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info', // 从环境变量中读取日志等级,如果没有设置,则默认为 'info'
format: winston.format.combine(
ecsFormat(),
winston.format((info, opts) => {
info.sn = info['trace.id'];
return info;
})(),
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), // 添加时间戳
winston.format.prettyPrint(), // 打印整个日志对象
winston.format.splat(), // 支持格式化的字符串
winston.format.printf(({ level, message, timestamp, site, sn }) => {
const labelStr = site ? ` [${colorLabel(site)}]` : '';
return `${timestamp} ${level} ${
sn ? `[${sn}]` : ''
}:${labelStr} ${message}`; // 自定义输出格式
}),
),
transports: transports,
});
replaceConsoleWithWinston();
};
function replaceConsoleWithWinston(): void {
const logger: Logger = newLogger();
// 替换所有 console 方法
console.log = (...msg) => logger.info(format(...msg));
console.error = (...msg) => logger.error(format(...msg));
console.warn = (...msg) => logger.warn(format(...msg));
console.debug = (...msg) => logger.debug(format(...msg));
}
export function newLogger(site?: string, extra?: Record<string, string>) {
const log = logger.child({ site, ...extra });
log.exitOnError = false;
return log;
}
export class TraceLogger {
private logger: Logger;
// ms 时间戳
private start_time: number = moment().valueOf();
constructor() {
this.logger = logger.child({ trace_type: 'request' });
logger.exitOnError = false;
}
info(msg: string, meta: any) {
if (!Config.config.global.trace) {
return;
}
this.logger.info(msg, meta, {
time_label: moment().valueOf() - this.start_time,
});
}
}
interface UDPTransportOptions extends Transport.TransportStreamOptions {
port: number;
host: string;
}
export class UDPTransport extends Transport {
private client: Socket;
private options: { port: number; host: string };
constructor(options: UDPTransportOptions) {
super(options as Transport.TransportStreamOptions);
this.options = {
host: options.host,
port: options.port,
};
this.client = dgram.createSocket('udp4');
this.client.unref();
}
log(
info: any,
callback: (error: Error | null, bytes: number | boolean) => void,
): void {
this.sendLog(info, (err: Error | null) => {
this.emit('logged', !err);
callback(err, !err);
});
}
close(): void {
this.client.disconnect();
}
private sendLog(
info: any,
callback: (error: Error | null, bytes?: number | boolean) => void,
): void {
let buffer: Buffer = Buffer.from(JSON.stringify(info));
// 设置UDP数据包的最大长度
const MAX_UDP_SIZE = 5000; // 这个值根据您的网络环境可能需要调整
// 如果数据包大小超过最大长度,则截取
if (buffer.length > MAX_UDP_SIZE) {
buffer = buffer.slice(0, MAX_UDP_SIZE);
}
/* eslint-disable @typescript-eslint/no-empty-function */
this.client.send(
buffer,
0,
buffer.length,
this.options.port,
this.options.host,
callback || function () {},
);
/* eslint-enable @typescript-eslint/no-empty-function */
}
}
let client: net.Socket | undefined;
export async function SaveMessagesToLogstash(
msg: ChatRequest,
other: { [key: string]: any } = {},
) {
const { enable = false, host, port } = Config.config.global?.msg_saver || {};
if (!enable || !port || !host) {
return;
}
if (!client) {
client = new net.Socket();
client.connect(port, host, () => {
console.log('Connected to Logstash via TCP');
});
client.on('error', (err) => {
console.error(`TCP connection error: ${err.message}`);
client?.destroy();
client = undefined;
});
}
return new Promise((resolve, reject) => {
const message =
JSON.stringify({
...msg,
prompt: undefined,
type: 'chat',
'@timestamp': new Date().toISOString(),
}) + '\n';
client?.write(message, 'utf8', (err) => {
if (err) {
console.error(`Failed to send log: ${err.message}`);
client?.destroy();
client = undefined;
}
resolve(null);
});
});
}