main
js 87 lines 2.36 KB
Raw
1 /**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @flow
8 */
9
10 // Helpers to patch console.logs to avoid logging during side-effect free
11 // replaying on render function. This currently only patches the object
12 // lazily which won't cover if the log function was extracted eagerly.
13 // We could also eagerly patch the method.
14
15 let disabledDepth = 0;
16 let prevLog;
17 let prevInfo;
18 let prevWarn;
19 let prevError;
20 let prevGroup;
21 let prevGroupCollapsed;
22 let prevGroupEnd;
23
24 function disabledLog() {}
25 disabledLog.__reactDisabledLog = true;
26
27 export function disableLogs(): void {
28 if (__DEV__) {
29 if (disabledDepth === 0) {
30 /* eslint-disable react-internal/no-production-logging */
31 prevLog = console.log;
32 prevInfo = console.info;
33 prevWarn = console.warn;
34 prevError = console.error;
35 prevGroup = console.group;
36 prevGroupCollapsed = console.groupCollapsed;
37 prevGroupEnd = console.groupEnd;
38 // https://github.com/facebook/react/issues/19099
39 const props = {
40 configurable: true,
41 enumerable: true,
42 value: disabledLog,
43 writable: true,
44 };
45 // $FlowFixMe[cannot-write] Flow thinks console is immutable.
46 Object.defineProperties(console, {
47 info: props,
48 log: props,
49 warn: props,
50 error: props,
51 group: props,
52 groupCollapsed: props,
53 groupEnd: props,
54 });
55 }
56 disabledDepth++;
57 }
58 }
59
60 export function reenableLogs(): void {
61 if (__DEV__) {
62 disabledDepth--;
63 if (disabledDepth === 0) {
64 const props = {
65 configurable: true,
66 enumerable: true,
67 writable: true,
68 };
69 // $FlowFixMe[cannot-write] Flow thinks console is immutable.
70 Object.defineProperties(console, {
71 log: {...props, value: prevLog},
72 info: {...props, value: prevInfo},
73 warn: {...props, value: prevWarn},
74 error: {...props, value: prevError},
75 group: {...props, value: prevGroup},
76 groupCollapsed: {...props, value: prevGroupCollapsed},
77 groupEnd: {...props, value: prevGroupEnd},
78 });
79 }
80 if (disabledDepth < 0) {
81 console.error(
82 'disabledDepth fell below zero. ' +
83 'This is a bug in React. Please file an issue.',
84 );
85 }
86 }
87 }