@rife/logger 0.0.6-beta.1 → 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.
Files changed (55) hide show
  1. package/dist/cjs/common.cjs +51 -0
  2. package/dist/cjs/env.cjs +40 -0
  3. package/dist/cjs/index.cjs +60 -0
  4. package/dist/cjs/pino/index.cjs +158 -0
  5. package/dist/cjs/pino/rotate.cjs +72 -0
  6. package/dist/cjs/pino/worker/pino-file.cjs +3353 -0
  7. package/dist/cjs/pino/worker/pino-pretty.cjs +2870 -0
  8. package/dist/cjs/pino/worker/pino-rotate.cjs +604 -0
  9. package/dist/cjs/pino/worker/pino-worker.cjs +3666 -0
  10. package/dist/cjs/pino/worker/thread-stream.cjs +172 -0
  11. package/dist/cjs/test.cjs +36 -0
  12. package/dist/cjs/trace.cjs +52 -0
  13. package/dist/esm/common.mjs +8 -0
  14. package/dist/esm/env.mjs +5 -0
  15. package/dist/esm/index.mjs +3 -0
  16. package/dist/esm/pino/index.mjs +116 -0
  17. package/dist/esm/pino/rotate.mjs +40 -0
  18. package/dist/esm/pino/worker/pino-file.cjs +3353 -0
  19. package/dist/esm/pino/worker/pino-pretty.cjs +2870 -0
  20. package/dist/esm/pino/worker/pino-rotate.cjs +604 -0
  21. package/dist/esm/pino/worker/pino-worker.cjs +3666 -0
  22. package/dist/esm/pino/worker/thread-stream.cjs +172 -0
  23. package/dist/esm/test.mjs +32 -0
  24. package/dist/esm/trace.mjs +14 -0
  25. package/dist/worker/pino-file.cjs +3353 -0
  26. package/dist/worker/pino-pretty.cjs +2870 -0
  27. package/dist/worker/pino-rotate.cjs +604 -0
  28. package/dist/worker/pino-worker.cjs +3666 -0
  29. package/dist/worker/thread-stream.cjs +172 -0
  30. package/package.json +16 -19
  31. package/src/common.ts +4 -0
  32. package/src/pino/index.ts +120 -0
  33. package/src/test.ts +8 -3
  34. package/src/trace.ts +1 -2
  35. package/tsconfig.json +12 -12
  36. package/dist/env.d.ts +0 -2
  37. package/dist/env.js +0 -22
  38. package/dist/env.js.map +0 -1
  39. package/dist/index.d.ts +0 -1
  40. package/dist/index.js +0 -8
  41. package/dist/index.js.map +0 -1
  42. package/dist/pino.d.ts +0 -8
  43. package/dist/pino.js +0 -88
  44. package/dist/pino.js.map +0 -1
  45. package/dist/rotate.d.ts +0 -6
  46. package/dist/rotate.js +0 -35
  47. package/dist/rotate.js.map +0 -1
  48. package/dist/test.d.ts +0 -1
  49. package/dist/test.js +0 -23
  50. package/dist/test.js.map +0 -1
  51. package/dist/trace.d.ts +0 -3
  52. package/dist/trace.js +0 -35
  53. package/dist/trace.js.map +0 -1
  54. package/src/pino.ts +0 -80
  55. /package/src/{rotate.ts → pino/rotate.ts} +0 -0
@@ -0,0 +1,172 @@
1
+ var __webpack_modules__ = {
2
+ "../../node_modules/.pnpm/real-require@0.2.0/node_modules/real-require/src/index.js": function(module1) {
3
+ const realImport = new Function('modulePath', 'return import(modulePath)');
4
+ function realRequire(modulePath) {
5
+ if ('function' == typeof __non_webpack__require__) return __non_webpack__require__(modulePath);
6
+ return require(modulePath);
7
+ }
8
+ module1.exports = {
9
+ realImport,
10
+ realRequire
11
+ };
12
+ },
13
+ "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js": function(module1) {
14
+ "use strict";
15
+ const WRITE_INDEX = 4;
16
+ const READ_INDEX = 8;
17
+ module1.exports = {
18
+ WRITE_INDEX,
19
+ READ_INDEX
20
+ };
21
+ },
22
+ "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js": function(module1) {
23
+ "use strict";
24
+ const MAX_TIMEOUT = 1000;
25
+ 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);
38
+ };
39
+ check(1);
40
+ }
41
+ 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);
52
+ };
53
+ check(1);
54
+ }
55
+ module1.exports = {
56
+ wait,
57
+ waitDiff
58
+ };
59
+ },
60
+ worker_threads: function(module1) {
61
+ "use strict";
62
+ module1.exports = require("worker_threads");
63
+ }
64
+ };
65
+ var __webpack_module_cache__ = {};
66
+ function __webpack_require__(moduleId) {
67
+ var cachedModule = __webpack_module_cache__[moduleId];
68
+ if (void 0 !== cachedModule) return cachedModule.exports;
69
+ var module1 = __webpack_module_cache__[moduleId] = {
70
+ exports: {}
71
+ };
72
+ __webpack_modules__[moduleId](module1, module1.exports, __webpack_require__);
73
+ return module1.exports;
74
+ }
75
+ var __webpack_exports__ = {};
76
+ (()=>{
77
+ "use strict";
78
+ const { realImport, realRequire } = __webpack_require__("../../node_modules/.pnpm/real-require@0.2.0/node_modules/real-require/src/index.js");
79
+ 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");
82
+ const { dataBuf, filename, stateBuf } = workerData;
83
+ let destination;
84
+ const state = new Int32Array(stateBuf);
85
+ const data = Buffer.from(dataBuf);
86
+ async function start() {
87
+ let worker;
88
+ 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);
95
+ } catch (error) {
96
+ if (('ENOTDIR' === error.code || 'ERR_MODULE_NOT_FOUND' === error.code) && filename.startsWith('file://')) worker = realRequire(decodeURIComponent(filename.replace('file://', '')));
97
+ else if (void 0 === error.code || 'ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING' === error.code) try {
98
+ worker = realRequire(decodeURIComponent(filename.replace('win32' === process.platform ? 'file:///' : 'file://', '')));
99
+ } catch {
100
+ throw error;
101
+ }
102
+ else throw error;
103
+ }
104
+ if ('object' == typeof worker) worker = worker.default;
105
+ if ('object' == typeof worker) worker = worker.default;
106
+ destination = await worker(workerData.workerData);
107
+ destination.on('error', function(err) {
108
+ Atomics.store(state, WRITE_INDEX, -2);
109
+ Atomics.notify(state, WRITE_INDEX);
110
+ Atomics.store(state, READ_INDEX, -2);
111
+ Atomics.notify(state, READ_INDEX);
112
+ parentPort.postMessage({
113
+ code: 'ERROR',
114
+ err
115
+ });
116
+ });
117
+ destination.on('close', function() {
118
+ const end = Atomics.load(state, WRITE_INDEX);
119
+ Atomics.store(state, READ_INDEX, end);
120
+ Atomics.notify(state, READ_INDEX);
121
+ setImmediate(()=>{
122
+ process.exit(0);
123
+ });
124
+ });
125
+ }
126
+ start().then(function() {
127
+ parentPort.postMessage({
128
+ code: 'READY'
129
+ });
130
+ process.nextTick(run);
131
+ });
132
+ function run() {
133
+ const current = Atomics.load(state, READ_INDEX);
134
+ const end = Atomics.load(state, WRITE_INDEX);
135
+ if (end === current) return void (end === data.length ? waitDiff(state, READ_INDEX, end, 1 / 0, run) : waitDiff(state, WRITE_INDEX, end, 1 / 0, run));
136
+ if (-1 === end) return void destination.end();
137
+ const toWrite = data.toString('utf8', current, end);
138
+ const res = destination.write(toWrite);
139
+ if (res) {
140
+ Atomics.store(state, READ_INDEX, end);
141
+ Atomics.notify(state, READ_INDEX);
142
+ setImmediate(run);
143
+ } else destination.once('drain', function() {
144
+ Atomics.store(state, READ_INDEX, end);
145
+ Atomics.notify(state, READ_INDEX);
146
+ run();
147
+ });
148
+ }
149
+ process.on('unhandledRejection', function(err) {
150
+ parentPort.postMessage({
151
+ code: 'ERROR',
152
+ err
153
+ });
154
+ process.exit(1);
155
+ });
156
+ process.on('uncaughtException', function(err) {
157
+ parentPort.postMessage({
158
+ code: 'ERROR',
159
+ err
160
+ });
161
+ process.exit(1);
162
+ });
163
+ process.once('exit', (exitCode)=>{
164
+ if (0 !== exitCode) return void process.exit(exitCode);
165
+ if (destination?.writableNeedDrain && !destination?.writableEnded) parentPort.postMessage({
166
+ code: 'WARNING',
167
+ err: new Error('ThreadStream: process exited before destination stream was drained. this may indicate that the destination stream try to write to a another missing stream')
168
+ });
169
+ process.exit(0);
170
+ });
171
+ })();
172
+ module.exports = __webpack_exports__;
package/package.json CHANGED
@@ -1,25 +1,25 @@
1
1
  {
2
2
  "name": "@rife/logger",
3
- "version": "0.0.6-beta.1",
3
+ "version": "0.0.6-beta.11",
4
4
  "description": "",
5
- "main": "./dist/index.js",
5
+ "type": "module",
6
6
  "types": "./src/index.ts",
7
7
  "exports": {
8
8
  ".": {
9
- "require": "./dist/index.js",
10
- "import": "./dist/index.js",
11
- "types": "./src/index.ts"
9
+ "types": "./src/index.ts",
10
+ "require": "./dist/cjs/index.cjs",
11
+ "import": "./dist/esm/index.mjs"
12
12
  },
13
13
  "./pino": {
14
- "require": "./dist/pino.js",
15
- "import": "./dist/pino.js",
16
- "types": "./src/pino.ts"
14
+ "types": "./src/pino/index.ts",
15
+ "require": "./dist/cjs/pino/index.cjs",
16
+ "import": "./dist/esm/pino/index.mjs"
17
17
  }
18
18
  },
19
19
  "typesVersions": {
20
20
  "*": {
21
21
  "pino": [
22
- "./src/pino.ts"
22
+ "./src/pino"
23
23
  ]
24
24
  }
25
25
  },
@@ -28,23 +28,20 @@
28
28
  "src/**/*",
29
29
  "tsconfig.json"
30
30
  ],
31
- "keywords": [],
32
- "author": "",
33
- "license": "ISC",
34
31
  "dependencies": {
35
- "pino": "^9.6.0",
36
- "pino-http": "^10.4.0",
37
- "pino-pretty": "^13.0.0",
32
+ "pino": "^10.1.0",
33
+ "pino-pretty": "^13.1.2",
38
34
  "pino-std-serializers": "^7.0.0",
39
- "rotating-file-stream": "^3.2.5"
35
+ "rotating-file-stream": "^3.2.7"
40
36
  },
41
37
  "devDependencies": {
42
- "@rife/cli": "0.0.6-beta.1"
38
+ "thread-stream": "*",
39
+ "@rife/cli": "0.0.6-beta.16",
40
+ "@rife/plugin-rstack": "0.0.1-beta.15"
43
41
  },
44
42
  "scripts": {
45
43
  "dev": "rife dev",
46
44
  "build": "rife build",
47
- "lint": "eslint . --fix",
48
- "release": "pnpm publish --registry https://registry.npmjs.org --no-git-checks"
45
+ "release": "rife release"
49
46
  }
50
47
  }
package/src/common.ts ADDED
@@ -0,0 +1,4 @@
1
+ import path from 'path';
2
+
3
+ export const isEsm = path.extname(__filename) === '.mjs';
4
+ export const isCjs = !isEsm;
@@ -0,0 +1,120 @@
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
+ }
package/src/test.ts CHANGED
@@ -6,9 +6,14 @@ import { genTraceId } from './trace';
6
6
 
7
7
  const { logger } = createLogger();
8
8
 
9
- logger.info({ time: 1, level: 1, hostname: 1, pid: 1, c: 2 }, '123');
9
+ logger.info({ a: 999 }, '1');
10
10
 
11
11
  const start = performance.now();
12
- logger.info({ duration: performance.now() - start, id: genTraceId() });
12
+ logger.info({ duration: Math.round(performance.now() - start), traceId: genTraceId() });
13
13
 
14
- console.log(module);
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
@@ -7,8 +7,7 @@ export function runInTrace<T>(data: any, fn: (...args: any[]) => T): T {
7
7
  }
8
8
 
9
9
  export function genTraceId() {
10
- // crypto 680
11
- return crypto.randomUUID();
10
+ return crypto.randomUUID().replaceAll('-', '');
12
11
  }
13
12
 
14
13
  export function getTraceId() {
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
+ }
package/dist/env.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export declare const isProd: () => boolean;
2
- export declare const isDev: () => boolean;
package/dist/env.js DELETED
@@ -1,22 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- function _export(target, all) {
6
- for(var name in all)Object.defineProperty(target, name, {
7
- enumerable: true,
8
- get: all[name]
9
- });
10
- }
11
- _export(exports, {
12
- isDev: function() {
13
- return isDev;
14
- },
15
- isProd: function() {
16
- return isProd;
17
- }
18
- });
19
- const isProd = ()=>process.env.NODE_ENV === 'production';
20
- const isDev = ()=>!isProd();
21
-
22
- //# sourceMappingURL=env.js.map
package/dist/env.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/env.ts"],"sourcesContent":["export const isProd = () => process.env.NODE_ENV === 'production';\n\nexport const isDev = () => !isProd();\n"],"names":["isDev","isProd","process","env","NODE_ENV"],"mappings":";;;;;;;;;;;IAEaA,KAAK;eAALA;;IAFAC,MAAM;eAANA;;;AAAN,MAAMA,SAAS,IAAMC,QAAQC,GAAG,CAACC,QAAQ,KAAK;AAE9C,MAAMJ,QAAQ,IAAM,CAACC"}
package/dist/index.d.ts DELETED
@@ -1 +0,0 @@
1
- export * from './trace';
package/dist/index.js DELETED
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- const _export_star = require("@swc/helpers/_/_export_star");
6
- _export_star._(require("./trace"), exports);
7
-
8
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './trace';\n"],"names":[],"mappings":";;;;;uBAAc"}
package/dist/pino.d.ts DELETED
@@ -1,8 +0,0 @@
1
- export declare namespace ILogger {
2
- interface Options {
3
- }
4
- }
5
- export declare function createLogger(options?: ILogger.Options): {
6
- logger: import("pino").Logger<never, boolean>;
7
- express: () => (req: any, res: any, next: any) => void;
8
- };
package/dist/pino.js DELETED
@@ -1,88 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- Object.defineProperty(exports, "createLogger", {
6
- enumerable: true,
7
- get: function() {
8
- return createLogger;
9
- }
10
- });
11
- const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
12
- const _pino = /*#__PURE__*/ _interop_require_default._(require("pino"));
13
- const _env = require("./env");
14
- const _trace = require("./trace");
15
- function getPinoConfig() {
16
- const targets = [];
17
- if ((0, _env.isDev)()) {
18
- targets.push({
19
- level: 'debug',
20
- target: 'pino-pretty',
21
- options: {}
22
- });
23
- }
24
- targets.push({
25
- level: 'debug',
26
- target: './rotate',
27
- options: {
28
- path: './.logs/'
29
- }
30
- });
31
- const config = {
32
- transport: {
33
- targets
34
- },
35
- mixin (data) {
36
- // {"level":30,"time":1726065716643,"pid":21968,"hostname":"Win-LH"}
37
- // 基础字段不能重复 删除掉
38
- delete data.level;
39
- delete data.time;
40
- delete data.pid;
41
- delete data.hostname;
42
- if (!data?.traceId) {
43
- return {
44
- traceId: (0, _trace.getTraceId)()
45
- };
46
- }
47
- return {};
48
- }
49
- };
50
- return config;
51
- }
52
- const startTime = Symbol('startTime');
53
- function createLogger(options) {
54
- const logger = (0, _pino.default)({
55
- ...getPinoConfig()
56
- });
57
- const express = ()=>{
58
- const { mapHttpRequest, mapHttpResponse } = require('pino-std-serializers');
59
- return (req, res, next)=>{
60
- const response = res;
61
- response[startTime] = response[startTime] || Date.now();
62
- const traceId = req.headers['trace-id'] || (0, _trace.genTraceId)();
63
- const onComplete = ()=>{
64
- res.removeListener('close', onComplete);
65
- res.removeListener('finish', onComplete);
66
- res.removeListener('error', onComplete);
67
- const duration = Date.now() - response[startTime];
68
- logger.info({
69
- duration,
70
- request: mapHttpRequest(req).req,
71
- response: mapHttpResponse(res).res
72
- }, 'request');
73
- };
74
- res.on('close', onComplete);
75
- res.on('finish', onComplete);
76
- res.on('error', onComplete);
77
- (0, _trace.runInTrace)({
78
- traceId
79
- }, next);
80
- };
81
- };
82
- return {
83
- logger,
84
- express
85
- };
86
- }
87
-
88
- //# sourceMappingURL=pino.js.map
package/dist/pino.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/pino.ts"],"sourcesContent":["import pino from 'pino';\r\n// https://github.com/pinojs/pino/blob/master/docs/api.md\r\n\r\nimport { isDev } from './env';\r\nimport { genTraceId, getTraceId, runInTrace } from './trace';\r\n\r\nexport namespace ILogger {\r\n export interface Options {}\r\n}\r\n\r\nfunction getPinoConfig() {\r\n const targets: any = [];\r\n\r\n if (isDev()) {\r\n targets.push({\r\n level: 'debug',\r\n target: 'pino-pretty', // must be installed separately,\r\n options: {},\r\n });\r\n }\r\n\r\n targets.push({\r\n level: 'debug',\r\n target: './rotate',\r\n options: { path: './.logs/' },\r\n });\r\n\r\n const config: pino.LoggerOptions = {\r\n transport: { targets },\r\n mixin(data: any) {\r\n // {\"level\":30,\"time\":1726065716643,\"pid\":21968,\"hostname\":\"Win-LH\"}\r\n // 基础字段不能重复 删除掉\r\n delete data.level;\r\n delete data.time;\r\n delete data.pid;\r\n delete data.hostname;\r\n if (!data?.traceId) {\r\n return { traceId: getTraceId() };\r\n }\r\n return {};\r\n },\r\n };\r\n\r\n return config;\r\n}\r\n\r\nconst startTime = Symbol('startTime');\r\n\r\nexport function createLogger(options?: ILogger.Options) {\r\n const logger = pino({\r\n ...getPinoConfig(),\r\n });\r\n\r\n const express = () => {\r\n const { mapHttpRequest, mapHttpResponse } = require('pino-std-serializers') as typeof import('pino-std-serializers');\r\n\r\n return (req: any, res: any, next: any) => {\r\n const response: any = res;\r\n response[startTime] = response[startTime] || Date.now();\r\n const traceId = req.headers['trace-id'] || genTraceId();\r\n\r\n const onComplete = () => {\r\n res.removeListener('close', onComplete);\r\n res.removeListener('finish', onComplete);\r\n res.removeListener('error', onComplete);\r\n const duration = Date.now() - response[startTime];\r\n\r\n logger.info({ duration, request: mapHttpRequest(req).req, response: mapHttpResponse(res).res }, 'request');\r\n };\r\n\r\n res.on('close', onComplete);\r\n res.on('finish', onComplete);\r\n res.on('error', onComplete);\r\n\r\n runInTrace({ traceId }, next);\r\n };\r\n };\r\n\r\n return { logger, express };\r\n}\r\n"],"names":["createLogger","getPinoConfig","targets","isDev","push","level","target","options","path","config","transport","mixin","data","time","pid","hostname","traceId","getTraceId","startTime","Symbol","logger","pino","express","mapHttpRequest","mapHttpResponse","require","req","res","next","response","Date","now","headers","genTraceId","onComplete","removeListener","duration","info","request","on","runInTrace"],"mappings":";;;;+BAgDgBA;;;eAAAA;;;;+DAhDC;qBAGK;uBAC6B;AAMnD,SAASC;IACL,MAAMC,UAAe,EAAE;IAEvB,IAAIC,IAAAA,UAAK,KAAI;QACTD,QAAQE,IAAI,CAAC;YACTC,OAAO;YACPC,QAAQ;YACRC,SAAS,CAAC;QACd;IACJ;IAEAL,QAAQE,IAAI,CAAC;QACTC,OAAO;QACPC,QAAQ;QACRC,SAAS;YAAEC,MAAM;QAAW;IAChC;IAEA,MAAMC,SAA6B;QAC/BC,WAAW;YAAER;QAAQ;QACrBS,OAAMC,IAAS;YACX,oEAAoE;YACpE,eAAe;YACf,OAAOA,KAAKP,KAAK;YACjB,OAAOO,KAAKC,IAAI;YAChB,OAAOD,KAAKE,GAAG;YACf,OAAOF,KAAKG,QAAQ;YACpB,IAAI,CAACH,MAAMI,SAAS;gBAChB,OAAO;oBAAEA,SAASC,IAAAA,iBAAU;gBAAG;YACnC;YACA,OAAO,CAAC;QACZ;IACJ;IAEA,OAAOR;AACX;AAEA,MAAMS,YAAYC,OAAO;AAElB,SAASnB,aAAaO,OAAyB;IAClD,MAAMa,SAASC,IAAAA,aAAI,EAAC;QAChB,GAAGpB,eAAe;IACtB;IAEA,MAAMqB,UAAU;QACZ,MAAM,EAAEC,cAAc,EAAEC,eAAe,EAAE,GAAGC,QAAQ;QAEpD,OAAO,CAACC,KAAUC,KAAUC;YACxB,MAAMC,WAAgBF;YACtBE,QAAQ,CAACX,UAAU,GAAGW,QAAQ,CAACX,UAAU,IAAIY,KAAKC,GAAG;YACrD,MAAMf,UAAUU,IAAIM,OAAO,CAAC,WAAW,IAAIC,IAAAA,iBAAU;YAErD,MAAMC,aAAa;gBACfP,IAAIQ,cAAc,CAAC,SAASD;gBAC5BP,IAAIQ,cAAc,CAAC,UAAUD;gBAC7BP,IAAIQ,cAAc,CAAC,SAASD;gBAC5B,MAAME,WAAWN,KAAKC,GAAG,KAAKF,QAAQ,CAACX,UAAU;gBAEjDE,OAAOiB,IAAI,CAAC;oBAAED;oBAAUE,SAASf,eAAeG,KAAKA,GAAG;oBAAEG,UAAUL,gBAAgBG,KAAKA,GAAG;gBAAC,GAAG;YACpG;YAEAA,IAAIY,EAAE,CAAC,SAASL;YAChBP,IAAIY,EAAE,CAAC,UAAUL;YACjBP,IAAIY,EAAE,CAAC,SAASL;YAEhBM,IAAAA,iBAAU,EAAC;gBAAExB;YAAQ,GAAGY;QAC5B;IACJ;IAEA,OAAO;QAAER;QAAQE;IAAQ;AAC7B"}
package/dist/rotate.d.ts DELETED
@@ -1,6 +0,0 @@
1
- import type { Options } from 'rotating-file-stream';
2
- export interface PinoRotatingFileStreamOptions extends Options {
3
- path: string;
4
- }
5
- declare const _default: (options: PinoRotatingFileStreamOptions) => import("rotating-file-stream").RotatingFileStream;
6
- export default _default;
package/dist/rotate.js DELETED
@@ -1,35 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- Object.defineProperty(exports, "default", {
6
- enumerable: true,
7
- get: function() {
8
- return _default;
9
- }
10
- });
11
- const generator = (time, index)=>{
12
- if (!time) {
13
- return 'server.log';
14
- }
15
- time = new Date(time);
16
- const month = String(time.getMonth() + 1).padStart(2, '0');
17
- const day = String(time.getDate()).padStart(2, '0');
18
- if (index) {
19
- const count = String(index).padStart(3, '0');
20
- return `server.${time.getFullYear()}${month}${day}-${count}.log`;
21
- }
22
- return `server.${time.getFullYear()}${month}${day}.log`;
23
- };
24
- const _default = (options)=>{
25
- const { createStream } = require('rotating-file-stream');
26
- const { path } = options;
27
- return createStream(generator, {
28
- size: '50M',
29
- maxSize: '500M',
30
- interval: '1d',
31
- path
32
- });
33
- };
34
-
35
- //# sourceMappingURL=rotate.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/rotate.ts"],"sourcesContent":["import type { Options } from 'rotating-file-stream';\n\nexport interface PinoRotatingFileStreamOptions extends Options {\n path: string;\n}\n\nconst generator = (time: number | Date, index?: number) => {\n if (!time) {\n return 'server.log';\n }\n time = new Date(time);\n\n const month = String(time.getMonth() + 1).padStart(2, '0');\n const day = String(time.getDate()).padStart(2, '0');\n if (index) {\n const count = String(index).padStart(3, '0');\n return `server.${time.getFullYear()}${month}${day}-${count}.log`;\n }\n return `server.${time.getFullYear()}${month}${day}.log`;\n};\n\nexport default (options: PinoRotatingFileStreamOptions) => {\n const { createStream } = require('rotating-file-stream') as typeof import('rotating-file-stream');\n\n const { path } = options;\n return createStream(generator, {\n size: '50M',\n maxSize: '500M',\n interval: '1d',\n path,\n });\n};\n"],"names":["generator","time","index","Date","month","String","getMonth","padStart","day","getDate","count","getFullYear","options","createStream","require","path","size","maxSize","interval"],"mappings":";;;;+BAqBA;;;eAAA;;;AAfA,MAAMA,YAAY,CAACC,MAAqBC;IACpC,IAAI,CAACD,MAAM;QACP,OAAO;IACX;IACAA,OAAO,IAAIE,KAAKF;IAEhB,MAAMG,QAAQC,OAAOJ,KAAKK,QAAQ,KAAK,GAAGC,QAAQ,CAAC,GAAG;IACtD,MAAMC,MAAMH,OAAOJ,KAAKQ,OAAO,IAAIF,QAAQ,CAAC,GAAG;IAC/C,IAAIL,OAAO;QACP,MAAMQ,QAAQL,OAAOH,OAAOK,QAAQ,CAAC,GAAG;QACxC,OAAO,CAAC,OAAO,EAAEN,KAAKU,WAAW,KAAKP,QAAQI,IAAI,CAAC,EAAEE,MAAM,IAAI,CAAC;IACpE;IACA,OAAO,CAAC,OAAO,EAAET,KAAKU,WAAW,KAAKP,QAAQI,IAAI,IAAI,CAAC;AAC3D;MAEA,WAAe,CAACI;IACZ,MAAM,EAAEC,YAAY,EAAE,GAAGC,QAAQ;IAEjC,MAAM,EAAEC,IAAI,EAAE,GAAGH;IACjB,OAAOC,aAAab,WAAW;QAC3BgB,MAAM;QACNC,SAAS;QACTC,UAAU;QACVH;IACJ;AACJ"}
package/dist/test.d.ts DELETED
@@ -1 +0,0 @@
1
- export {};
package/dist/test.js DELETED
@@ -1,23 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- const _pino = require("./pino");
6
- const _trace = require("./trace");
7
- process.env.NODE_ENV = 'development';
8
- const { logger } = (0, _pino.createLogger)();
9
- logger.info({
10
- time: 1,
11
- level: 1,
12
- hostname: 1,
13
- pid: 1,
14
- c: 2
15
- }, '123');
16
- const start = performance.now();
17
- logger.info({
18
- duration: performance.now() - start,
19
- id: (0, _trace.genTraceId)()
20
- });
21
- console.log(module);
22
-
23
- //# sourceMappingURL=test.js.map
package/dist/test.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/test.ts"],"sourcesContent":["process.env.NODE_ENV = 'development';\n// process.env.NODE_ENV = 'production';\n\nimport { createLogger } from './pino';\nimport { genTraceId } from './trace';\n\nconst { logger } = createLogger();\n\nlogger.info({ time: 1, level: 1, hostname: 1, pid: 1, c: 2 }, '123');\n\nconst start = performance.now();\nlogger.info({ duration: performance.now() - start, id: genTraceId() });\n\nconsole.log(module);\n"],"names":["process","env","NODE_ENV","logger","createLogger","info","time","level","hostname","pid","c","start","performance","now","duration","id","genTraceId","console","log","module"],"mappings":";;;;sBAG6B;uBACF;AAJ3BA,QAAQC,GAAG,CAACC,QAAQ,GAAG;AAMvB,MAAM,EAAEC,MAAM,EAAE,GAAGC,IAAAA,kBAAY;AAE/BD,OAAOE,IAAI,CAAC;IAAEC,MAAM;IAAGC,OAAO;IAAGC,UAAU;IAAGC,KAAK;IAAGC,GAAG;AAAE,GAAG;AAE9D,MAAMC,QAAQC,YAAYC,GAAG;AAC7BV,OAAOE,IAAI,CAAC;IAAES,UAAUF,YAAYC,GAAG,KAAKF;IAAOI,IAAIC,IAAAA,iBAAU;AAAG;AAEpEC,QAAQC,GAAG,CAACC"}