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

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.
@@ -1,5 +1,6 @@
1
+ "use strict";
1
2
  var __webpack_modules__ = {
2
- "../../node_modules/.pnpm/real-require@0.2.0/node_modules/real-require/src/index.js": function(module1) {
3
+ "../../node_modules/.pnpm/real-require@0.2.0/node_modules/real-require/src/index.js" (module1) {
3
4
  const realImport = new Function('modulePath', 'return import(modulePath)');
4
5
  function realRequire(modulePath) {
5
6
  if ('function' == typeof __non_webpack__require__) return __non_webpack__require__(modulePath);
@@ -10,7 +11,7 @@ var __webpack_modules__ = {
10
11
  realRequire
11
12
  };
12
13
  },
13
- "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js": function(module1) {
14
+ "../../node_modules/.pnpm/thread-stream@4.0.0/node_modules/thread-stream/lib/indexes.js" (module1) {
14
15
  "use strict";
15
16
  const WRITE_INDEX = 4;
16
17
  const READ_INDEX = 8;
@@ -19,45 +20,41 @@ var __webpack_modules__ = {
19
20
  READ_INDEX
20
21
  };
21
22
  },
22
- "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js": function(module1) {
23
+ "../../node_modules/.pnpm/thread-stream@4.0.0/node_modules/thread-stream/lib/wait.js" (module1) {
23
24
  "use strict";
24
- const MAX_TIMEOUT = 1000;
25
+ const WAIT_MS = 10000;
25
26
  function wait(state, index, expected, timeout, done) {
26
- const max = Date.now() + timeout;
27
- let current = Atomics.load(state, index);
28
- if (current === expected) return void done(null, 'ok');
29
- let prior = current;
30
- const check = (backoff)=>{
31
- if (Date.now() > max) done(null, 'timed-out');
32
- else setTimeout(()=>{
33
- prior = current;
34
- current = Atomics.load(state, index);
35
- if (current === prior) check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : 2 * backoff);
36
- else current === expected ? done(null, 'ok') : done(null, 'not-equal');
37
- }, backoff);
27
+ const max = timeout === 1 / 0 ? 1 / 0 : Date.now() + timeout;
28
+ const check = ()=>{
29
+ const current = Atomics.load(state, index);
30
+ if (current === expected) return void done(null, 'ok');
31
+ if (max !== 1 / 0 && Date.now() > max) return void done(null, 'timed-out');
32
+ const remaining = max === 1 / 0 ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max - Date.now()));
33
+ const result = Atomics.waitAsync(state, index, current, remaining);
34
+ if (result.async) result.value.then(check);
35
+ else setImmediate(check);
38
36
  };
39
- check(1);
37
+ check();
40
38
  }
41
39
  function waitDiff(state, index, expected, timeout, done) {
42
- const max = Date.now() + timeout;
43
- let current = Atomics.load(state, index);
44
- if (current !== expected) return void done(null, 'ok');
45
- const check = (backoff)=>{
46
- if (Date.now() > max) done(null, 'timed-out');
47
- else setTimeout(()=>{
48
- current = Atomics.load(state, index);
49
- if (current !== expected) done(null, 'ok');
50
- else check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : 2 * backoff);
51
- }, backoff);
40
+ const max = timeout === 1 / 0 ? 1 / 0 : Date.now() + timeout;
41
+ const check = ()=>{
42
+ const current = Atomics.load(state, index);
43
+ if (current !== expected) return void done(null, 'ok');
44
+ if (max !== 1 / 0 && Date.now() > max) return void done(null, 'timed-out');
45
+ const remaining = max === 1 / 0 ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max - Date.now()));
46
+ const result = Atomics.waitAsync(state, index, expected, remaining);
47
+ if (result.async) result.value.then(check);
48
+ else setImmediate(check);
52
49
  };
53
- check(1);
50
+ check();
54
51
  }
55
52
  module1.exports = {
56
53
  wait,
57
54
  waitDiff
58
55
  };
59
56
  },
60
- worker_threads: function(module1) {
57
+ worker_threads (module1) {
61
58
  "use strict";
62
59
  module1.exports = require("worker_threads");
63
60
  }
@@ -77,21 +74,17 @@ var __webpack_exports__ = {};
77
74
  "use strict";
78
75
  const { realImport, realRequire } = __webpack_require__("../../node_modules/.pnpm/real-require@0.2.0/node_modules/real-require/src/index.js");
79
76
  const { workerData, parentPort } = __webpack_require__("worker_threads");
80
- const { WRITE_INDEX, READ_INDEX } = __webpack_require__("../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js");
81
- const { waitDiff } = __webpack_require__("../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js");
77
+ const { WRITE_INDEX, READ_INDEX } = __webpack_require__("../../node_modules/.pnpm/thread-stream@4.0.0/node_modules/thread-stream/lib/indexes.js");
78
+ const { waitDiff } = __webpack_require__("../../node_modules/.pnpm/thread-stream@4.0.0/node_modules/thread-stream/lib/wait.js");
82
79
  const { dataBuf, filename, stateBuf } = workerData;
83
80
  let destination;
84
81
  const state = new Int32Array(stateBuf);
85
82
  const data = Buffer.from(dataBuf);
83
+ const keepAlive = setInterval(()=>{}, 3600000);
86
84
  async function start() {
87
85
  let worker;
88
86
  try {
89
- if (filename.endsWith('.ts') || filename.endsWith('.cts')) {
90
- if (process[Symbol.for('ts-node.register.instance')]) {
91
- if (process.env.TS_NODE_DEV) realRequire('ts-node-dev');
92
- } else realRequire('ts-node/register');
93
- worker = realRequire(decodeURIComponent(filename.replace('win32' === process.platform ? 'file:///' : 'file://', '')));
94
- } else worker = await realImport(filename);
87
+ worker = await realImport(filename);
95
88
  } catch (error) {
96
89
  if (('ENOTDIR' === error.code || 'ERR_MODULE_NOT_FOUND' === error.code) && filename.startsWith('file://')) worker = realRequire(decodeURIComponent(filename.replace('file://', '')));
97
90
  else if (void 0 === error.code || 'ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING' === error.code) try {
@@ -99,6 +92,14 @@ var __webpack_exports__ = {};
99
92
  } catch {
100
93
  throw error;
101
94
  }
95
+ else if (filename.endsWith('.ts') || filename.endsWith('.cts')) try {
96
+ if (process[Symbol.for('ts-node.register.instance')]) {
97
+ if (process.env.TS_NODE_DEV) realRequire('ts-node-dev');
98
+ } else realRequire('ts-node/register');
99
+ worker = realRequire(decodeURIComponent(filename.replace('win32' === process.platform ? 'file:///' : 'file://', '')));
100
+ } catch {
101
+ throw error;
102
+ }
102
103
  else throw error;
103
104
  }
104
105
  if ('object' == typeof worker) worker = worker.default;
@@ -118,6 +119,7 @@ var __webpack_exports__ = {};
118
119
  const end = Atomics.load(state, WRITE_INDEX);
119
120
  Atomics.store(state, READ_INDEX, end);
120
121
  Atomics.notify(state, READ_INDEX);
122
+ clearInterval(keepAlive);
121
123
  setImmediate(()=>{
122
124
  process.exit(0);
123
125
  });
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.12",
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.3",
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
- "thread-stream": "*",
39
- "@rife/cli": "0.0.6-beta.15",
40
- "@rife/plugin-rstack": "0.0.1-beta.11"
38
+ "thread-stream": "^4.0.0",
39
+ "@rife/cli": "0.0.6-beta.20",
40
+ "@rife/plugin-rstack": "0.0.1-beta.17"
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,122 @@
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
+ const traceId = data?.traceId;
57
+ delete data.traceId;
58
+ delete data.level;
59
+ delete data.time;
60
+ delete data.pid;
61
+ delete data.name;
62
+ delete data.hostname;
63
+ if (!traceId) {
64
+ return { traceId: getTraceId() };
65
+ }
66
+ return { traceId };
67
+ },
68
+ };
69
+
70
+ return config;
71
+ }
72
+
73
+ export function createLogger() {
74
+ const logger = pino({
75
+ // https://github.com/pinojs/pino/blob/main/docs/api.md#opt-serializers
76
+ base: { pid: process.pid },
77
+ messageKey: 'message',
78
+ errorKey: 'error',
79
+ timestamp: pino.stdTimeFunctions.epochTime,
80
+ // timestamp: process.env.NODE_ENV === 'production' ? pino.stdTimeFunctions.epochTime : pino.stdTimeFunctions.isoTime,
81
+ ...getPinoConfig(),
82
+ });
83
+
84
+ return { logger };
85
+ }
86
+
87
+ import type { SerializedRequest, SerializedResponse } from 'pino-std-serializers';
88
+
89
+ export type ExpressFormat = (info: ExpressInfo) => any;
90
+
91
+ export interface ExpressInfo {
92
+ duration: number;
93
+ request: SerializedRequest;
94
+ response: SerializedResponse;
95
+ }
96
+
97
+ export function useExpress(logger: any, format?: ExpressFormat) {
98
+ const serializers = require('pino-std-serializers') as typeof import('pino-std-serializers');
99
+ const mapHttpRequest = serializers.mapHttpRequest;
100
+ const mapHttpResponse = serializers.mapHttpResponse || (serializers as any).default.mapHttpResponse;
101
+ const startTime = Symbol();
102
+ return (req: any, res: any, next: any) => {
103
+ const response: any = res;
104
+ response[startTime] = response[startTime] || Date.now();
105
+ const traceId = req.headers['trace-id'] || genTraceId();
106
+ const onComplete = () => {
107
+ res.removeListener('close', onComplete);
108
+ res.removeListener('finish', onComplete);
109
+ res.removeListener('error', onComplete);
110
+ const duration = Date.now() - response[startTime];
111
+ const serializedRequest = mapHttpRequest(req).req;
112
+ const serializedResponse = mapHttpResponse(res).res;
113
+ const msg = `${serializedRequest.method} ${serializedRequest.url}`;
114
+ const info: ExpressInfo = { duration, request: serializedRequest, response: serializedResponse };
115
+ logger.info(format?.(info) || info, msg);
116
+ };
117
+ res.on('close', onComplete);
118
+ res.on('finish', onComplete);
119
+ res.on('error', onComplete);
120
+ runInTrace({ traceId }, next);
121
+ };
122
+ }
@@ -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,22 @@
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, runInTrace } 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
+
20
+ runInTrace({ traceId: genTraceId() }, () => {
21
+ log.info(1);
22
+ });
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
+ }