@lark-apaas/client-toolkit 1.1.4 → 1.1.5-logpanel-test.0

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.
@@ -21,7 +21,7 @@ function PageHoc(props) {
21
21
  type: 'PageScreenshot',
22
22
  data: imgEle.src
23
23
  });
24
- });
24
+ }).catch(()=>{});
25
25
  }, 1000);
26
26
  return ()=>clearTimeout(timer);
27
27
  }
@@ -9,7 +9,16 @@ const NotFound = ()=>{
9
9
  const navigate = useNavigate();
10
10
  const navigateRef = useUpdatingRef(navigate);
11
11
  useEffect(()=>{
12
- logger.error('404 Error: User attempted to access non-existent route:', location.pathname);
12
+ logger.log({
13
+ level: 'error',
14
+ args: [
15
+ `页面 ${location.pathname} 不存在`
16
+ ],
17
+ meta: {
18
+ repairMessage: `页面 ${location.pathname} 不存在,帮我创建`,
19
+ noStacktrace: true
20
+ }
21
+ });
13
22
  }, [
14
23
  location.pathname
15
24
  ]);
@@ -1,10 +1,10 @@
1
1
  import { logger } from "./logger.js";
2
2
  function interceptGlobalError() {
3
3
  window.addEventListener('error', (event)=>{
4
- logger.error('global error', event);
4
+ logger.error(event.error);
5
5
  });
6
6
  window.addEventListener('unhandledrejection', (event)=>{
7
- logger.error('global unhandledrejection', event);
7
+ logger.error(event.reason);
8
8
  });
9
9
  }
10
10
  export { interceptGlobalError };
@@ -20,94 +20,79 @@ export declare const noCategoryLogSchema: z.ZodObject<{
20
20
  message: z.ZodUnknown;
21
21
  args: z.ZodArray<z.ZodUnknown>;
22
22
  }, z.core.$strip>;
23
+ export declare const logStackFrameSchema: z.ZodObject<{
24
+ functionName: z.ZodString;
25
+ fileName: z.ZodString;
26
+ lineNumber: z.ZodNumber;
27
+ columnNumber: z.ZodNumber;
28
+ }, z.core.$strip>;
23
29
  export declare const levelSchema: z.ZodEnum<{
30
+ success: "success";
24
31
  info: "info";
25
32
  warn: "warn";
26
33
  error: "error";
27
34
  debug: "debug";
28
35
  }>;
29
- export declare const selectedLogSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
30
- type: z.ZodLiteral<"networkRequest">;
31
- level: z.ZodEnum<{
32
- info: "info";
33
- warn: "warn";
34
- error: "error";
35
- debug: "debug";
36
- }>;
37
- id: z.ZodString;
38
- data: z.ZodObject<{
39
- method: z.ZodString;
40
- status: z.ZodInt;
41
- statusText: z.ZodString;
42
- path: z.ZodString;
43
- requestData: z.ZodOptional<z.ZodUnknown>;
44
- requestParams: z.ZodOptional<z.ZodUnknown>;
45
- responseData: z.ZodOptional<z.ZodUnknown>;
46
- traceID: z.ZodString;
47
- }, z.core.$strip>;
48
- }, z.core.$strip>, z.ZodObject<{
49
- type: z.ZodLiteral<"routerError">;
50
- level: z.ZodEnum<{
51
- info: "info";
52
- warn: "warn";
53
- error: "error";
54
- debug: "debug";
55
- }>;
56
- id: z.ZodString;
57
- data: z.ZodObject<{
58
- path: z.ZodString;
59
- }, z.core.$strip>;
60
- }, z.core.$strip>, z.ZodObject<{
61
- type: z.ZodLiteral<"renderError">;
62
- level: z.ZodEnum<{
63
- info: "info";
64
- warn: "warn";
65
- error: "error";
66
- debug: "debug";
67
- }>;
68
- id: z.ZodString;
69
- data: z.ZodObject<{
70
- message: z.ZodString;
71
- stack: z.ZodString;
72
- }, z.core.$strip>;
73
- }, z.core.$strip>, z.ZodObject<{
74
- type: z.ZodLiteral<"globalError">;
75
- level: z.ZodEnum<{
76
- info: "info";
77
- warn: "warn";
78
- error: "error";
79
- debug: "debug";
80
- }>;
81
- id: z.ZodString;
82
- data: z.ZodObject<{
83
- message: z.ZodString;
84
- stack: z.ZodString;
85
- }, z.core.$strip>;
86
- }, z.core.$strip>, z.ZodObject<{
87
- type: z.ZodLiteral<"unhandledRejectionError">;
36
+ export declare const logMeta: z.ZodObject<{
37
+ stacktrace: z.ZodOptional<z.ZodArray<z.ZodObject<{
38
+ functionName: z.ZodString;
39
+ fileName: z.ZodString;
40
+ lineNumber: z.ZodNumber;
41
+ columnNumber: z.ZodNumber;
42
+ }, z.core.$strip>>>;
43
+ logTraceID: z.ZodOptional<z.ZodString>;
44
+ skipFrame: z.ZodOptional<z.ZodNumber>;
45
+ noStacktrace: z.ZodOptional<z.ZodBoolean>;
46
+ repairMessage: z.ZodOptional<z.ZodString>;
47
+ }, z.core.$strip>;
48
+ export declare const selectedLogSchema: z.ZodObject<{
49
+ type: z.ZodLiteral<"typedLogV2">;
88
50
  level: z.ZodEnum<{
51
+ success: "success";
89
52
  info: "info";
90
53
  warn: "warn";
91
54
  error: "error";
92
55
  debug: "debug";
93
56
  }>;
94
57
  id: z.ZodString;
95
- data: z.ZodObject<{
96
- message: z.ZodString;
97
- stack: z.ZodString;
58
+ args: z.ZodArray<z.ZodUnknown>;
59
+ meta: z.ZodObject<{
60
+ stacktrace: z.ZodOptional<z.ZodArray<z.ZodObject<{
61
+ functionName: z.ZodString;
62
+ fileName: z.ZodString;
63
+ lineNumber: z.ZodNumber;
64
+ columnNumber: z.ZodNumber;
65
+ }, z.core.$strip>>>;
66
+ logTraceID: z.ZodOptional<z.ZodString>;
67
+ skipFrame: z.ZodOptional<z.ZodNumber>;
68
+ noStacktrace: z.ZodOptional<z.ZodBoolean>;
69
+ repairMessage: z.ZodOptional<z.ZodString>;
98
70
  }, z.core.$strip>;
99
- }, z.core.$strip>, z.ZodObject<{
100
- type: z.ZodLiteral<"noCategory">;
71
+ }, z.core.$strip>;
72
+ export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'success';
73
+ export declare const logWithMetaSchema: z.ZodObject<{
101
74
  level: z.ZodEnum<{
75
+ success: "success";
102
76
  info: "info";
103
77
  warn: "warn";
104
78
  error: "error";
105
79
  debug: "debug";
106
80
  }>;
107
- id: z.ZodString;
108
- data: z.ZodObject<{
109
- message: z.ZodUnknown;
110
- args: z.ZodArray<z.ZodUnknown>;
81
+ args: z.ZodArray<z.ZodUnknown>;
82
+ meta: z.ZodObject<{
83
+ stacktrace: z.ZodOptional<z.ZodArray<z.ZodObject<{
84
+ functionName: z.ZodString;
85
+ fileName: z.ZodString;
86
+ lineNumber: z.ZodNumber;
87
+ columnNumber: z.ZodNumber;
88
+ }, z.core.$strip>>>;
89
+ logTraceID: z.ZodOptional<z.ZodString>;
90
+ skipFrame: z.ZodOptional<z.ZodNumber>;
91
+ noStacktrace: z.ZodOptional<z.ZodBoolean>;
92
+ repairMessage: z.ZodOptional<z.ZodString>;
111
93
  }, z.core.$strip>;
112
- }, z.core.$strip>], "type">;
94
+ }, z.core.$strip>;
95
+ export type LogStackFrame = z.infer<typeof logStackFrameSchema>;
96
+ export type LogWithMeta = z.infer<typeof logWithMetaSchema>;
97
+ export type LogMeta = z.infer<typeof logMeta>;
113
98
  export type SelectedLog = z.infer<typeof selectedLogSchema>;
@@ -20,48 +20,36 @@ const noCategoryLogSchema = zod.object({
20
20
  message: zod.unknown(),
21
21
  args: zod.array(zod.unknown())
22
22
  });
23
+ const logStackFrameSchema = zod.object({
24
+ functionName: zod.string(),
25
+ fileName: zod.string(),
26
+ lineNumber: zod.number(),
27
+ columnNumber: zod.number()
28
+ });
23
29
  const levelSchema = zod["enum"]([
24
30
  'info',
25
31
  'warn',
26
32
  'error',
27
- 'debug'
28
- ]);
29
- const selectedLogSchema = zod.discriminatedUnion('type', [
30
- zod.object({
31
- type: zod.literal('networkRequest'),
32
- level: levelSchema,
33
- id: zod.string(),
34
- data: networkRequestLogSchema
35
- }),
36
- zod.object({
37
- type: zod.literal('routerError'),
38
- level: levelSchema,
39
- id: zod.string(),
40
- data: routerErrorSchema
41
- }),
42
- zod.object({
43
- type: zod.literal('renderError'),
44
- level: levelSchema,
45
- id: zod.string(),
46
- data: genericErrorSchema
47
- }),
48
- zod.object({
49
- type: zod.literal('globalError'),
50
- level: levelSchema,
51
- id: zod.string(),
52
- data: genericErrorSchema
53
- }),
54
- zod.object({
55
- type: zod.literal('unhandledRejectionError'),
56
- level: levelSchema,
57
- id: zod.string(),
58
- data: genericErrorSchema
59
- }),
60
- zod.object({
61
- type: zod.literal('noCategory'),
62
- level: levelSchema,
63
- id: zod.string(),
64
- data: noCategoryLogSchema
65
- })
33
+ 'debug',
34
+ 'success'
66
35
  ]);
67
- export { genericErrorSchema, levelSchema, networkRequestLogSchema, noCategoryLogSchema, routerErrorSchema, selectedLogSchema };
36
+ const logMeta = zod.object({
37
+ stacktrace: zod.optional(zod.array(logStackFrameSchema)),
38
+ logTraceID: zod.optional(zod.string()),
39
+ skipFrame: zod.optional(zod.number()),
40
+ noStacktrace: zod.optional(zod.boolean()),
41
+ repairMessage: zod.optional(zod.string())
42
+ });
43
+ const selectedLogSchema = zod.object({
44
+ type: zod.literal('typedLogV2'),
45
+ level: levelSchema,
46
+ id: zod.string(),
47
+ args: zod.array(zod.unknown()),
48
+ meta: logMeta
49
+ });
50
+ const logWithMetaSchema = zod.object({
51
+ level: levelSchema,
52
+ args: zod.array(zod.unknown()),
53
+ meta: logMeta
54
+ });
55
+ export { genericErrorSchema, levelSchema, logMeta, logStackFrameSchema, logWithMetaSchema, networkRequestLogSchema, noCategoryLogSchema, routerErrorSchema, selectedLogSchema };
@@ -1,7 +1,10 @@
1
+ import { LogWithMeta } from './log-types';
1
2
  export type LogInterceptor = (originLogger: typeof logger) => typeof logger;
2
3
  export declare let logger: {
3
4
  debug(message: any, ...args: any[]): void;
4
5
  info(message: any, ...args: any[]): void;
5
6
  warn(message: any, ...args: any[]): void;
6
7
  error(message: any, ...args: any[]): void;
8
+ success(message: any, ...args: any[]): void;
9
+ log({ level, args }: LogWithMeta): void;
7
10
  };
@@ -51,6 +51,12 @@ let logger = {
51
51
  },
52
52
  error (message, ...args) {
53
53
  if (shouldLog('error')) console.error(...getFormattedPrefix('error'), message, ...args);
54
+ },
55
+ success (message, ...args) {
56
+ if (shouldLog('success')) console.log(...getFormattedPrefix('success'), message, ...args);
57
+ },
58
+ log ({ level, args }) {
59
+ if (shouldLog(level)) console.log(...getFormattedPrefix(level), ...args);
54
60
  }
55
61
  };
56
62
  for (const interceptor of interceptors)logger = interceptor(logger);
@@ -1,2 +1,5 @@
1
1
  import { type LogInterceptor } from './logger';
2
+ import { logStackFrameSchema } from './log-types';
3
+ import z from 'zod';
4
+ export declare function getStacktrace(): Promise<z.infer<typeof logStackFrameSchema>[]>;
2
5
  export declare const interceptors: LogInterceptor[];
@@ -1,8 +1,7 @@
1
- import { logger as external_logger_js_logger } from "./logger.js";
2
- import { SourceMapConsumer } from "source-map";
3
- import { normalizeBasePath } from "../utils/utils.js";
1
+ import { SourceMapConsumer as external_source_map_SourceMapConsumer } from "source-map";
2
+ import "../utils/utils.js";
4
3
  import { mappingText } from "./source-map-mappings-wasm.js";
5
- import { genericErrorSchema, networkRequestLogSchema, noCategoryLogSchema, routerErrorSchema } from "./log-types.js";
4
+ import stacktrace_js from "stacktrace-js";
6
5
  function hexToBuffer(hexString) {
7
6
  const hex = hexString.replace(/\s/g, '').toUpperCase();
8
7
  if (!/^[0-9A-F]+$/.test(hex)) throw new Error('Invalid hex string');
@@ -15,246 +14,147 @@ function hexToBuffer(hexString) {
15
14
  }
16
15
  return buffer;
17
16
  }
18
- SourceMapConsumer.initialize({
17
+ external_source_map_SourceMapConsumer.initialize({
19
18
  'lib/mappings.wasm': hexToBuffer(mappingText)
20
19
  });
21
- async function getSourceMap() {
22
- let sourceMapContent = '';
20
+ const mapStacktrace = (stacktrace)=>stacktrace.map((frame)=>({
21
+ functionName: frame.functionName || '',
22
+ fileName: frame.fileName || '',
23
+ lineNumber: frame.lineNumber || 0,
24
+ columnNumber: frame.columnNumber || 0
25
+ }));
26
+ async function sendSelectedLog(logWithoutID) {
23
27
  try {
24
- const basePath = normalizeBasePath(process.env.CLIENT_BASE_PATH);
25
- const res = await fetch(`${basePath}/main.js.map`);
26
- sourceMapContent = await res.text();
27
- } catch (e) {
28
- external_logger_js_logger.warn('get main.js.map error', e);
29
- }
30
- return sourceMapContent;
31
- }
32
- async function parseSourceMap(stack) {
33
- try {
34
- const sourceMapContent = await getSourceMap();
35
- if (!sourceMapContent) return stack;
36
- const consumer = await new SourceMapConsumer(JSON.parse(sourceMapContent));
37
- const lines = stack.split('\n');
38
- for(let i = 0; i < lines.length; i++){
39
- const line = lines[i];
40
- const match = line.match(/\((.*main\.js):(\d+):(\d+)\)/);
41
- if (match) {
42
- const [fullMatch, , lineNum, colNum] = match;
43
- const originalPosition = consumer.originalPositionFor({
44
- line: Number(lineNum),
45
- column: Number(colNum)
46
- });
47
- if (originalPosition.source) {
48
- let originalPositionStr = `(${originalPosition.source}:${originalPosition.line}:${originalPosition.column})`;
49
- originalPositionStr = originalPositionStr.replace('webpack://fullstack-nestjs-template/', '');
50
- lines[i] = line.replace(fullMatch, originalPositionStr);
51
- }
28
+ const log = {
29
+ ...logWithoutID,
30
+ id: crypto.randomUUID()
31
+ };
32
+ const newParts = [];
33
+ for(let i = 0; i < log.args.length; i++)if (log.args[i] instanceof Error) {
34
+ const error = log.args[i];
35
+ const newError = {
36
+ message: error.message,
37
+ stack: error.stack
38
+ };
39
+ if (!log.meta.stacktrace) {
40
+ const stacktrace = await stacktrace_js.fromError(error);
41
+ log.meta.stacktrace = mapStacktrace(stacktrace);
52
42
  }
43
+ newParts.push(newError.message, newError);
44
+ } else newParts.push(log.args[i]);
45
+ if (!log.meta.stacktrace) {
46
+ let frames = await getStacktrace();
47
+ const firstFrameIndex = frames.findIndex((frame)=>!frame.fileName.includes('node_modules/@lark-apaas/client-toolkit/lib/logger'));
48
+ frames = -1 === firstFrameIndex ? [] : frames.slice(firstFrameIndex);
49
+ log.meta.stacktrace = frames;
53
50
  }
54
- return lines.join('\n');
55
- } catch (e) {
56
- external_logger_js_logger.warn('recover code position error', e);
57
- return stack;
58
- }
59
- }
60
- function sendSelectedLog(log) {
61
- const logWithID = {
62
- ...log,
63
- id: crypto.randomUUID()
64
- };
65
- try {
66
- const logJSON = JSON.stringify(logWithID);
51
+ if (void 0 === log.meta.skipFrame) log.meta.skipFrame = 2;
52
+ const logJSON = JSON.stringify(log);
53
+ console.log(JSON.parse(logJSON));
67
54
  console.log(logJSON);
68
55
  if (window.parent !== window) try {
69
56
  window.parent.postMessage({
70
57
  type: 'SELECTED_LOG',
71
58
  payload: logJSON
72
59
  }, '*');
73
- } catch (e) {
74
- external_logger_js_logger.warn('post selected log to parent iframe error', e);
75
- }
76
- } catch (e) {
77
- external_logger_js_logger.warn('send selected log error', e);
78
- }
60
+ } catch (e) {}
61
+ } catch (e) {}
79
62
  }
80
- const comprehensiveInterceptor = (logger)=>({
63
+ async function getStacktrace() {
64
+ const stacktrace = await stacktrace_js.get();
65
+ const frames = mapStacktrace(stacktrace);
66
+ return frames;
67
+ }
68
+ async function sendTypedLogV2(logWithMeta) {
69
+ sendSelectedLog({
70
+ type: 'typedLogV2',
71
+ level: logWithMeta.level,
72
+ args: logWithMeta.args,
73
+ meta: logWithMeta.meta
74
+ });
75
+ }
76
+ const typedLogInterceptor = (logger)=>({
77
+ debug: (message, ...args)=>{
78
+ try {
79
+ logger.debug(message, ...args);
80
+ } catch (e) {}
81
+ sendTypedLogV2({
82
+ level: 'debug',
83
+ args: [
84
+ message,
85
+ ...args
86
+ ],
87
+ meta: {}
88
+ });
89
+ },
81
90
  info: (message, ...args)=>{
82
91
  try {
83
92
  logger.info(message, ...args);
84
- } catch (e) {
85
- logger.warn('info log error', e);
86
- }
87
- if (message && 'object' == typeof message && 'HTTP Request' === message.type) return;
88
- if (message && 'object' == typeof message && 'HTTP Response' === message.type) {
89
- let requestData = message.data;
90
- if ('string' == typeof requestData) try {
91
- requestData = JSON.parse(requestData);
92
- } catch (e) {
93
- logger.warn('parse request data error', e);
94
- }
95
- const info = networkRequestLogSchema.safeParse({
96
- method: message.method || '',
97
- status: message.status || 0,
98
- statusText: message.statusText || '',
99
- path: message.url || '',
100
- requestData,
101
- requestParams: message.params,
102
- responseData: message.responseData,
103
- traceID: message.headers?.['X-Trace-ID'] || ''
104
- });
105
- if (info.success) sendSelectedLog({
106
- type: 'networkRequest',
107
- level: 'info',
108
- data: info.data
109
- });
110
- return;
111
- }
112
- sendSelectedLog({
113
- type: 'noCategory',
93
+ } catch (e) {}
94
+ sendTypedLogV2({
114
95
  level: 'info',
115
- data: {
96
+ args: [
116
97
  message,
117
- args
118
- }
98
+ ...args
99
+ ],
100
+ meta: {}
119
101
  });
120
102
  },
121
103
  error: (message, ...args)=>{
122
104
  try {
123
105
  logger.error(message, ...args);
124
- } catch (e) {
125
- logger.warn('error log error', e);
126
- }
127
- if (message && 'object' == typeof message && 'HTTP Request' === message.type) return;
128
- if (message && 'object' == typeof message && 'HTTP Response' === message.type) {
129
- let requestData = message.data;
130
- if ('string' == typeof requestData) try {
131
- requestData = JSON.parse(requestData);
132
- } catch (e) {
133
- logger.warn('parse request data error', e);
134
- }
135
- const info = networkRequestLogSchema.safeParse({
136
- method: message.method || '',
137
- status: message.status || 0,
138
- statusText: message.statusText || '',
139
- path: message.url || '',
140
- requestData,
141
- requestParams: message.params,
142
- responseData: message.responseData,
143
- traceID: message.headers?.['X-Trace-ID'] || ''
144
- });
145
- if (info.success) sendSelectedLog({
146
- type: 'networkRequest',
147
- level: 'error',
148
- data: info.data
149
- });
150
- return;
151
- }
152
- if ('RenderError' === message) return void (async ()=>{
153
- const error = args[0];
154
- if (error && error instanceof Error) {
155
- const stack = await parseSourceMap(error.stack || '');
156
- sendSelectedLog({
157
- type: 'renderError',
158
- level: 'error',
159
- data: {
160
- message: error.message,
161
- stack
162
- }
163
- });
164
- }
165
- })();
166
- if ('404 Error: User attempted to access non-existent route:' === message) {
167
- const path = args[0] || '';
168
- const data = routerErrorSchema.safeParse({
169
- path
170
- });
171
- if (data.success) return void sendSelectedLog({
172
- level: 'error',
173
- type: 'routerError',
174
- data: data.data
175
- });
176
- }
177
- if ('global error' === message) {
178
- const error = args[0];
179
- if (error && error instanceof ErrorEvent) {
180
- const data = genericErrorSchema.safeParse({
181
- message: error?.error?.message || '',
182
- stack: error?.error?.stack || ''
183
- });
184
- if (data.success) return void (async ()=>{
185
- const stack = await parseSourceMap(data.data.stack || '');
186
- sendSelectedLog({
187
- type: 'globalError',
188
- level: 'error',
189
- data: {
190
- ...data.data,
191
- stack
192
- }
193
- });
194
- })();
195
- }
196
- }
197
- if ('global unhandledrejection' === message) {
198
- const error = args[0];
199
- if (error && error instanceof PromiseRejectionEvent) {
200
- const data = genericErrorSchema.safeParse({
201
- message: error?.reason?.message || '',
202
- stack: error?.reason?.stack || ''
203
- });
204
- if (data.success) return void (async ()=>{
205
- const stack = await parseSourceMap(data.data.stack || '');
206
- sendSelectedLog({
207
- type: 'unhandledRejectionError',
208
- level: 'error',
209
- data: {
210
- ...data.data,
211
- stack
212
- }
213
- });
214
- })();
215
- }
216
- }
217
- sendSelectedLog({
218
- type: 'noCategory',
106
+ } catch (e) {}
107
+ sendTypedLogV2({
219
108
  level: 'error',
220
- data: noCategoryLogSchema.parse({
109
+ args: [
221
110
  message,
222
- args
223
- })
111
+ ...args
112
+ ],
113
+ meta: {}
224
114
  });
225
115
  },
226
116
  warn: (message, ...args)=>{
227
117
  try {
228
118
  logger.warn(message, ...args);
229
- } catch (e) {
230
- logger.warn('warn log error', e);
231
- }
232
- sendSelectedLog({
233
- type: 'noCategory',
119
+ } catch (e) {}
120
+ sendTypedLogV2({
234
121
  level: 'warn',
235
- data: {
122
+ args: [
236
123
  message,
237
- args
238
- }
124
+ ...args
125
+ ],
126
+ meta: {}
239
127
  });
240
128
  },
241
- debug: (message, ...args)=>{
129
+ success: (message, ...args)=>{
242
130
  try {
243
- logger.debug(message, ...args);
244
- } catch (e) {
245
- logger.warn('debug log error', e);
246
- }
247
- sendSelectedLog({
248
- type: 'noCategory',
249
- level: 'debug',
250
- data: {
131
+ logger.success(message, ...args);
132
+ } catch (e) {}
133
+ sendTypedLogV2({
134
+ level: 'success',
135
+ args: [
251
136
  message,
252
- args
253
- }
137
+ ...args
138
+ ],
139
+ meta: {}
140
+ });
141
+ },
142
+ log: ({ level, args, meta })=>{
143
+ try {
144
+ logger.log({
145
+ level,
146
+ args,
147
+ meta
148
+ });
149
+ } catch (e) {}
150
+ sendTypedLogV2({
151
+ level,
152
+ args,
153
+ meta: meta || {}
254
154
  });
255
155
  }
256
156
  });
257
157
  const interceptors = 'production' !== process.env.NODE_ENV ? [
258
- comprehensiveInterceptor
259
- ] : null;
260
- export { interceptors };
158
+ typedLogInterceptor
159
+ ] : [];
160
+ export { getStacktrace, interceptors };
@@ -1,4 +1,4 @@
1
- import { type AxiosInstance } from 'axios';
1
+ import { AxiosInstance } from 'axios';
2
2
  /**
3
3
  * axios配置内容:拦截器、日志等
4
4
  */
@@ -1,59 +1,66 @@
1
1
  import axios from "axios";
2
2
  import { logger } from "../apis/logger.js";
3
- function getRequestLogInfo(config) {
4
- return {
5
- url: config?.url,
6
- method: config?.method?.toUpperCase(),
7
- params: config?.params,
8
- data: config?.data,
9
- headers: {
10
- ...config?.headers,
11
- 'X-Suda-Csrf-Token': config?.headers['X-Suda-Csrf-Token'] ? '[REDACTED]' : void 0,
12
- Authorization: config?.headers.Authorization ? '[REDACTED]' : void 0
3
+ import { getStacktrace } from "../logger/selected-logs.js";
4
+ async function logResponse(ok, response) {
5
+ const okToTextMap = {
6
+ success: '请求成功:',
7
+ error: '请求失败:'
8
+ };
9
+ const parts = [
10
+ okToTextMap[ok],
11
+ (response.config.url || '').split('?')[0].replace(/^\/spark\/p\/app_\w+/, ''),
12
+ ' - ',
13
+ Date.now() - response.config._startTime,
14
+ 'ms'
15
+ ];
16
+ const logTraceID = response.headers['x-log-trace-id'];
17
+ const args = [
18
+ '请求参数:',
19
+ response.config.data,
20
+ '返回数据:',
21
+ response.data,
22
+ '请求摘要:',
23
+ {
24
+ TraceID: logTraceID,
25
+ 状态: `${response.statusText}[状态码${response.status}]`,
26
+ 时间: `${new Date().toLocaleString()}`
13
27
  }
28
+ ];
29
+ const requestUUID = response.config._requestUUID;
30
+ const stacktrace = await requestStacktraceMap.get(requestUUID);
31
+ const logMeta = {
32
+ logTraceID
14
33
  };
34
+ if (stacktrace) logMeta.stacktrace = stacktrace;
35
+ logger.log({
36
+ level: ok,
37
+ args: [
38
+ parts.join(''),
39
+ ...args
40
+ ],
41
+ meta: {
42
+ logTraceID
43
+ }
44
+ });
15
45
  }
46
+ const requestStacktraceMap = new Map();
16
47
  function initAxiosConfig(axiosInstance) {
17
48
  if (!axiosInstance) axiosInstance = axios;
18
49
  axiosInstance.interceptors.request.use((config)=>{
50
+ const requestUUID = crypto.randomUUID();
51
+ const stacktrace = getStacktrace();
52
+ requestStacktraceMap.set(requestUUID, stacktrace);
53
+ config._requestUUID = requestUUID;
19
54
  config._startTime = Date.now();
20
55
  const csrfToken = window.csrfToken;
21
56
  if (csrfToken) config.headers['X-Suda-Csrf-Token'] = csrfToken;
22
- config.headers['X-Trace-ID'] = crypto.randomUUID();
23
- logger.info({
24
- type: 'HTTP Request',
25
- ...getRequestLogInfo(config)
26
- });
27
57
  return config;
28
- }, (error)=>{
29
- logger.error({
30
- type: 'HTTP Request',
31
- ...getRequestLogInfo(error.config),
32
- message: error.message,
33
- stack: error.stack
34
- });
35
- return Promise.reject(error);
36
- });
58
+ }, (error)=>Promise.reject(error));
37
59
  axiosInstance.interceptors.response.use((response)=>{
38
- logger.info({
39
- type: 'HTTP Response',
40
- ...getRequestLogInfo(response.config),
41
- status: response.status,
42
- statusText: response.statusText,
43
- responseData: response.data,
44
- responseTime: Date.now() - response.config._startTime
45
- });
60
+ logResponse('success', response);
46
61
  return response;
47
62
  }, (error)=>{
48
- logger.error({
49
- type: 'HTTP Response',
50
- ...getRequestLogInfo(error.config),
51
- status: error.response?.status,
52
- statusText: error.response?.statusText,
53
- message: error.message,
54
- responseData: error.response?.data,
55
- responseTime: Date.now() - error.config._startTime
56
- });
63
+ logResponse('error', error.response);
57
64
  return Promise.reject(error);
58
65
  });
59
66
  }
@@ -1,6 +1,10 @@
1
1
  import { getPreviewParentOrigin } from "./getParentOrigin.js";
2
2
  function postMessage(message, targetOrigin) {
3
- window.parent.postMessage(message, targetOrigin ?? getPreviewParentOrigin());
3
+ try {
4
+ window.parent.postMessage(message, targetOrigin ?? getPreviewParentOrigin());
5
+ } catch (e) {
6
+ console.error('postMessage error', e);
7
+ }
4
8
  }
5
9
  function isOutgoingMessage(msg, type) {
6
10
  return msg.type === type;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-apaas/client-toolkit",
3
- "version": "1.1.4",
3
+ "version": "1.1.5-logpanel-test.0",
4
4
  "types": "./lib/index.d.ts",
5
5
  "main": "./lib/index.js",
6
6
  "files": [
@@ -92,6 +92,7 @@
92
92
  "sockjs-client": "^1.6.1",
93
93
  "sonner": "~2.0.0",
94
94
  "source-map": "^0.7.6",
95
+ "stacktrace-js": "^2.0.2",
95
96
  "tailwind-merge": "~2.0.0",
96
97
  "tailwind-variants": "0.3.1",
97
98
  "tailwindcss-animate": "^1.0.7",