@rife/logger 0.0.6-beta.10 → 0.0.6-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rife/logger",
3
- "version": "0.0.6-beta.10",
3
+ "version": "0.0.6-beta.11",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./src/index.ts",
@@ -29,15 +29,15 @@
29
29
  "tsconfig.json"
30
30
  ],
31
31
  "dependencies": {
32
- "pino": "^9.8.0",
33
- "pino-pretty": "^13.1.1",
32
+ "pino": "^10.1.0",
33
+ "pino-pretty": "^13.1.2",
34
34
  "pino-std-serializers": "^7.0.0",
35
- "rotating-file-stream": "^3.2.6"
35
+ "rotating-file-stream": "^3.2.7"
36
36
  },
37
37
  "devDependencies": {
38
38
  "thread-stream": "*",
39
- "@rife/cli": "0.0.6-beta.15",
40
- "@rife/plugin-rstack": "0.0.1-beta.11"
39
+ "@rife/cli": "0.0.6-beta.16",
40
+ "@rife/plugin-rstack": "0.0.1-beta.15"
41
41
  },
42
42
  "scripts": {
43
43
  "dev": "rife dev",
package/src/common.ts CHANGED
@@ -1,4 +1,4 @@
1
- import path from 'path';
2
-
3
- export const isEsm = path.extname(__filename) === '.mjs';
4
- export const isCjs = !isEsm;
1
+ import path from 'path';
2
+
3
+ export const isEsm = path.extname(__filename) === '.mjs';
4
+ export const isCjs = !isEsm;
package/src/pino/index.ts CHANGED
@@ -1,102 +1,120 @@
1
- import path from 'path';
2
-
3
- import pino from 'pino';
4
-
5
- import { isEsm } from '../common';
6
- import { genTraceId, getTraceId, runInTrace } from '../trace';
7
-
8
- declare var PINO_RSPACK_PLUGIN: any;
9
-
10
- // https://github.com/pinojs/pino/blob/master/docs/api.md
11
- function getPinoConfig() {
12
- const targets: any = [];
13
-
14
- if (typeof PINO_RSPACK_PLUGIN !== 'undefined') {
15
- // 打包单文件的时候自动拷贝worker
16
- (globalThis as any).__bundlerPathsOverrides = {
17
- 'pino-pretty': path.join(__dirname, './worker/pino-pretty.cjs'),
18
- 'pino-worker': path.join(__dirname, './worker/pino-worker.cjs'),
19
- './rotate.cjs': path.join(__dirname, './worker/pino-rotate.cjs'),
20
- 'pino/file': path.join(__dirname, './worker/pino-file.cjs'),
21
- 'thread-stream-worker': path.join(__dirname, './worker/thread-stream.cjs'),
22
- ...(globalThis as any).__bundlerPathsOverrides,
23
- };
24
- }
25
-
26
- if (process.env.NODE_ENV === 'production') {
27
- } else {
28
- targets.push({
29
- level: 'debug',
30
- target: 'pino-pretty', // must be installed separately,
31
- options: {
32
- // https://github.com/pinojs/pino-pretty?tab=readme-ov-file#options
33
- ignore: 'pid',
34
- messageKey: 'message',
35
- },
36
- });
37
- }
38
-
39
- targets.push({
40
- level: 'debug',
41
- target: `./rotate${isEsm ? '.mjs' : '.cjs'}`,
42
- options: { path: './logs/' },
43
- });
44
-
45
- const config: pino.LoggerOptions = {
46
- transport: { targets },
47
- mixin(data: any) {
48
- // {"level":30,"time":1726065716643,"pid":21968,"hostname":"Win-LH"}
49
- // 基础字段不能重复 删除掉
50
- delete data.level;
51
- delete data.time;
52
- delete data.pid;
53
- delete data.name;
54
- delete data.hostname;
55
- if (!data?.traceId) {
56
- return { traceId: getTraceId() };
57
- }
58
- return {};
59
- },
60
- };
61
-
62
- return config;
63
- }
64
-
65
- export function createLogger() {
66
- const logger = pino({
67
- // https://github.com/pinojs/pino/blob/main/docs/api.md#opt-serializers
68
- base: { pid: process.pid },
69
- messageKey: 'message',
70
- errorKey: 'error',
71
- timestamp: pino.stdTimeFunctions.epochTime,
72
- // timestamp: process.env.NODE_ENV === 'production' ? pino.stdTimeFunctions.epochTime : pino.stdTimeFunctions.isoTime,
73
- ...getPinoConfig(),
74
- });
75
-
76
- return { logger };
77
- }
78
-
79
- // export function express(logger: any) {
80
- // const { mapHttpRequest, mapHttpResponse } = require('pino-std-serializers') as typeof import('pino-std-serializers');
81
-
82
- // return (req: any, res: any, next: any) => {
83
- // const response: any = res;
84
- // response[startTime] = response[startTime] || Date.now();
85
- // const traceId = req.headers['trace-id'] || genTraceId();
86
-
87
- // const onComplete = () => {
88
- // res.removeListener('close', onComplete);
89
- // res.removeListener('finish', onComplete);
90
- // res.removeListener('error', onComplete);
91
- // const duration = Date.now() - response[startTime];
92
-
93
- // logger.info({ duration, request: mapHttpRequest(req).req, response: mapHttpResponse(res).res }, 'request');
94
- // };
95
-
96
- // res.on('close', onComplete);
97
- // res.on('finish', onComplete);
98
- // res.on('error', onComplete);
99
-
100
- // runInTrace({ traceId }, next);
101
- // };
102
- // }
1
+ import path from 'path';
2
+
3
+ import pino from 'pino';
4
+
5
+ import { genTraceId, getTraceId, runInTrace } from '../trace';
6
+
7
+ declare var __isNodeSingleFileBundle: any;
8
+ declare var __isVite: any;
9
+
10
+ // https://github.com/pinojs/pino/blob/master/docs/api.md
11
+ function getPinoConfig() {
12
+ const targets: any = [];
13
+
14
+ const rotate = `./rotate${path.extname(__filename)}`;
15
+ targets.push({
16
+ level: 'debug',
17
+ target: rotate,
18
+ options: { path: './logs/' },
19
+ });
20
+
21
+ if (
22
+ typeof __isNodeSingleFileBundle !== 'undefined' ||
23
+ typeof __isVite !== 'undefined' || // remix
24
+ (global as any)?.__remix_devServerHooks || // remix
25
+ process.env.NODE_ENV !== 'development'
26
+ ) {
27
+ // 打包单文件的时候自动拷贝worker
28
+ (globalThis as any).__bundlerPathsOverrides = {
29
+ 'pino-pretty': path.join(__dirname, './worker/pino-pretty.cjs'),
30
+ 'pino-worker': path.join(__dirname, './worker/pino-worker.cjs'),
31
+ [rotate]: path.join(__dirname, './worker/pino-rotate.cjs'),
32
+ 'pino/file': path.join(__dirname, './worker/pino-file.cjs'),
33
+ 'thread-stream-worker': path.join(__dirname, './worker/thread-stream.cjs'),
34
+ ...(globalThis as any).__bundlerPathsOverrides,
35
+ };
36
+ }
37
+
38
+ if (process.env.NODE_ENV === 'production') {
39
+ } else {
40
+ targets.push({
41
+ level: 'debug',
42
+ target: 'pino-pretty', // must be installed separately,
43
+ options: {
44
+ // https://github.com/pinojs/pino-pretty?tab=readme-ov-file#options
45
+ ignore: 'pid',
46
+ messageKey: 'message',
47
+ },
48
+ });
49
+ }
50
+
51
+ const config: pino.LoggerOptions = {
52
+ transport: { targets },
53
+ mixin(data: any) {
54
+ // {"level":30,"time":1726065716643,"pid":21968,"hostname":"Win-LH"}
55
+ // 基础字段不能重复 删除掉
56
+ delete data.level;
57
+ delete data.time;
58
+ delete data.pid;
59
+ delete data.name;
60
+ delete data.hostname;
61
+ if (!data?.traceId) {
62
+ return { traceId: getTraceId() };
63
+ }
64
+ return {};
65
+ },
66
+ };
67
+
68
+ return config;
69
+ }
70
+
71
+ export function createLogger() {
72
+ const logger = pino({
73
+ // https://github.com/pinojs/pino/blob/main/docs/api.md#opt-serializers
74
+ base: { pid: process.pid },
75
+ messageKey: 'message',
76
+ errorKey: 'error',
77
+ timestamp: pino.stdTimeFunctions.epochTime,
78
+ // timestamp: process.env.NODE_ENV === 'production' ? pino.stdTimeFunctions.epochTime : pino.stdTimeFunctions.isoTime,
79
+ ...getPinoConfig(),
80
+ });
81
+
82
+ return { logger };
83
+ }
84
+
85
+ import type { SerializedRequest, SerializedResponse } from 'pino-std-serializers';
86
+
87
+ export type ExpressFormat = (info: ExpressInfo) => any;
88
+
89
+ export interface ExpressInfo {
90
+ duration: number;
91
+ request: SerializedRequest;
92
+ response: SerializedResponse;
93
+ }
94
+
95
+ export function useExpress(logger: any, format?: ExpressFormat) {
96
+ const serializers = require('pino-std-serializers') as typeof import('pino-std-serializers');
97
+ const mapHttpRequest = serializers.mapHttpRequest;
98
+ const mapHttpResponse = serializers.mapHttpResponse || (serializers as any).default.mapHttpResponse;
99
+ const startTime = Symbol();
100
+ return (req: any, res: any, next: any) => {
101
+ const response: any = res;
102
+ response[startTime] = response[startTime] || Date.now();
103
+ const traceId = req.headers['trace-id'] || genTraceId();
104
+ const onComplete = () => {
105
+ res.removeListener('close', onComplete);
106
+ res.removeListener('finish', onComplete);
107
+ res.removeListener('error', onComplete);
108
+ const duration = Date.now() - response[startTime];
109
+ const serializedRequest = mapHttpRequest(req).req;
110
+ const serializedResponse = mapHttpResponse(res).res;
111
+ const msg = `${serializedRequest.method} ${serializedRequest.url}`;
112
+ const info: ExpressInfo = { duration, request: serializedRequest, response: serializedResponse };
113
+ logger.info(format?.(info) || info, msg);
114
+ };
115
+ res.on('close', onComplete);
116
+ res.on('finish', onComplete);
117
+ res.on('error', onComplete);
118
+ runInTrace({ traceId }, next);
119
+ };
120
+ }
@@ -1,32 +1,32 @@
1
- import type { Options } from 'rotating-file-stream';
2
-
3
- export interface PinoRotatingFileStreamOptions extends Options {
4
- path: string;
5
- }
6
-
7
- const generator = (time: number | Date, index?: number) => {
8
- if (!time) {
9
- return 'server.log';
10
- }
11
- time = new Date(time);
12
-
13
- const month = String(time.getMonth() + 1).padStart(2, '0');
14
- const day = String(time.getDate()).padStart(2, '0');
15
- if (index) {
16
- const count = String(index).padStart(3, '0');
17
- return `server.${time.getFullYear()}${month}${day}-${count}.log`;
18
- }
19
- return `server.${time.getFullYear()}${month}${day}.log`;
20
- };
21
-
22
- export default (options: PinoRotatingFileStreamOptions) => {
23
- const { createStream } = require('rotating-file-stream') as typeof import('rotating-file-stream');
24
-
25
- const { path } = options;
26
- return createStream(generator, {
27
- size: '50M',
28
- maxSize: '500M',
29
- interval: '1d',
30
- path,
31
- });
32
- };
1
+ import type { Options } from 'rotating-file-stream';
2
+
3
+ export interface PinoRotatingFileStreamOptions extends Options {
4
+ path: string;
5
+ }
6
+
7
+ const generator = (time: number | Date, index?: number) => {
8
+ if (!time) {
9
+ return 'server.log';
10
+ }
11
+ time = new Date(time);
12
+
13
+ const month = String(time.getMonth() + 1).padStart(2, '0');
14
+ const day = String(time.getDate()).padStart(2, '0');
15
+ if (index) {
16
+ const count = String(index).padStart(3, '0');
17
+ return `server.${time.getFullYear()}${month}${day}-${count}.log`;
18
+ }
19
+ return `server.${time.getFullYear()}${month}${day}.log`;
20
+ };
21
+
22
+ export default (options: PinoRotatingFileStreamOptions) => {
23
+ const { createStream } = require('rotating-file-stream') as typeof import('rotating-file-stream');
24
+
25
+ const { path } = options;
26
+ return createStream(generator, {
27
+ size: '50M',
28
+ maxSize: '500M',
29
+ interval: '1d',
30
+ path,
31
+ });
32
+ };
package/src/test.ts CHANGED
@@ -1,19 +1,19 @@
1
- process.env.NODE_ENV = 'development';
2
- // process.env.NODE_ENV = 'production';
3
-
4
- import { createLogger } from './pino';
5
- import { genTraceId } from './trace';
6
-
7
- const { logger } = createLogger();
8
-
9
- logger.info({ a: 999 }, '1');
10
-
11
- const start = performance.now();
12
- logger.info({ duration: Math.round(performance.now() - start), traceId: genTraceId() });
13
-
14
- const log = logger.child({ name: 'name123', traceId: genTraceId() }, { msgPrefix: '[123] ' });
15
-
16
- log.info(2);
17
- log.info({ c: 1, name: '========' }, 'name overide');
18
- log.error(new Error('cause', { cause: new Error('789') }));
19
- log.error({ error: new Error('error data'), data: 2 });
1
+ process.env.NODE_ENV = 'development';
2
+ // process.env.NODE_ENV = 'production';
3
+
4
+ import { createLogger } from './pino';
5
+ import { genTraceId } from './trace';
6
+
7
+ const { logger } = createLogger();
8
+
9
+ logger.info({ a: 999 }, '1');
10
+
11
+ const start = performance.now();
12
+ logger.info({ duration: Math.round(performance.now() - start), traceId: genTraceId() });
13
+
14
+ const log = logger.child({ name: 'name123', traceId: genTraceId() }, { msgPrefix: '[123] ' });
15
+
16
+ log.error(new Error('cause', { cause: new Error('789') }));
17
+ log.error({ error: new Error('error data'), data: 2 });
18
+ log.info({ c: 1, name: '========' }, 'name overide');
19
+ log.info(1);
package/src/trace.ts CHANGED
@@ -1,15 +1,15 @@
1
- import { AsyncLocalStorage } from 'async_hooks';
2
-
3
- const als = new AsyncLocalStorage<{ traceId: string } & any>();
4
-
5
- export function runInTrace<T>(data: any, fn: (...args: any[]) => T): T {
6
- return als.run(data, fn);
7
- }
8
-
9
- export function genTraceId() {
10
- return crypto.randomUUID().replaceAll('-', '');
11
- }
12
-
13
- export function getTraceId() {
14
- return als.getStore()?.traceId;
15
- }
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+
3
+ const als = new AsyncLocalStorage<{ traceId: string } & any>();
4
+
5
+ export function runInTrace<T>(data: any, fn: (...args: any[]) => T): T {
6
+ return als.run(data, fn);
7
+ }
8
+
9
+ export function genTraceId() {
10
+ return crypto.randomUUID().replaceAll('-', '');
11
+ }
12
+
13
+ export function getTraceId() {
14
+ return als.getStore()?.traceId;
15
+ }
package/tsconfig.json CHANGED
@@ -1,12 +1,12 @@
1
- {
2
- "extends": "@rife/config/tsconfig.json", // 继承 packages 目录下通用配置
3
- "compilerOptions": {
4
- "outDir": "dist",
5
- "declaration": true,
6
- "baseUrl": ".",
7
- "paths": {
8
- "@/*": ["./src/*"]
9
- }
10
- },
11
- "include": ["./src/**/*"]
12
- }
1
+ {
2
+ "extends": "@rife/config/tsconfig.json", // 继承 packages 目录下通用配置
3
+ "compilerOptions": {
4
+ "outDir": "dist",
5
+ "declaration": true,
6
+ "baseUrl": ".",
7
+ "paths": {
8
+ "@/*": ["./src/*"]
9
+ }
10
+ },
11
+ "include": ["./src/**/*"]
12
+ }