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

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 (44) 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 +107 -0
  5. package/dist/cjs/pino/rotate.cjs +72 -0
  6. package/dist/cjs/test.cjs +36 -0
  7. package/dist/cjs/trace.cjs +52 -0
  8. package/dist/esm/common.mjs +8 -0
  9. package/dist/esm/env.mjs +5 -0
  10. package/dist/esm/index.mjs +3 -0
  11. package/dist/esm/pino/index.mjs +67 -0
  12. package/dist/esm/pino/rotate.mjs +40 -0
  13. package/dist/esm/test.mjs +32 -0
  14. package/dist/esm/trace.mjs +14 -0
  15. package/dist/worker/pino-file.cjs +3522 -0
  16. package/dist/worker/pino-pretty.cjs +2856 -0
  17. package/dist/worker/pino-rotate.cjs +604 -0
  18. package/dist/worker/pino-worker.cjs +3835 -0
  19. package/dist/worker/thread-stream.cjs +172 -0
  20. package/package.json +16 -19
  21. package/src/common.ts +4 -0
  22. package/src/pino/index.ts +102 -0
  23. package/src/{rotate.ts → pino/rotate.ts} +32 -32
  24. package/src/test.ts +19 -14
  25. package/src/trace.ts +15 -16
  26. package/dist/env.d.ts +0 -2
  27. package/dist/env.js +0 -22
  28. package/dist/env.js.map +0 -1
  29. package/dist/index.d.ts +0 -1
  30. package/dist/index.js +0 -8
  31. package/dist/index.js.map +0 -1
  32. package/dist/pino.d.ts +0 -8
  33. package/dist/pino.js +0 -88
  34. package/dist/pino.js.map +0 -1
  35. package/dist/rotate.d.ts +0 -6
  36. package/dist/rotate.js +0 -35
  37. package/dist/rotate.js.map +0 -1
  38. package/dist/test.d.ts +0 -1
  39. package/dist/test.js +0 -23
  40. package/dist/test.js.map +0 -1
  41. package/dist/trace.d.ts +0 -3
  42. package/dist/trace.js +0 -35
  43. package/dist/trace.js.map +0 -1
  44. package/src/pino.ts +0 -80
@@ -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.10",
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": "^9.8.0",
33
+ "pino-pretty": "^13.1.1",
38
34
  "pino-std-serializers": "^7.0.0",
39
- "rotating-file-stream": "^3.2.5"
35
+ "rotating-file-stream": "^3.2.6"
40
36
  },
41
37
  "devDependencies": {
42
- "@rife/cli": "0.0.6-beta.1"
38
+ "thread-stream": "*",
39
+ "@rife/cli": "0.0.6-beta.15",
40
+ "@rife/plugin-rstack": "0.0.1-beta.11"
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,102 @@
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,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,14 +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({ time: 1, level: 1, hostname: 1, pid: 1, c: 2 }, '123');
10
-
11
- const start = performance.now();
12
- logger.info({ duration: performance.now() - start, id: genTraceId() });
13
-
14
- console.log(module);
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 });
package/src/trace.ts CHANGED
@@ -1,16 +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
- // crypto 680
11
- return crypto.randomUUID();
12
- }
13
-
14
- export function getTraceId() {
15
- return als.getStore()?.traceId;
16
- }
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/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;