Skip to content

Commit a8ae161

Browse files
committed
log: custom logging using loglevel & enum LogLevel
1 parent effebaa commit a8ae161

File tree

11 files changed

+115
-58
lines changed

11 files changed

+115
-58
lines changed

apps/plugin/plugin-src/code.ts

Lines changed: 31 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
postSettingsChanged,
99
} from "backend";
1010
import { nodesToJSON } from "backend/src/altNodes/jsonNodeConversion";
11+
import { log, error } from "backend/src/common/log";
1112
import { retrieveGenericSolidUIColors } from "backend/src/common/retrieveUI/retrieveColors";
1213
import { flutterCodeGenTextStyles } from "backend/src/flutter/flutterMain";
1314
import { htmlCodeGenTextStyles } from "backend/src/html/htmlMain";
@@ -41,10 +42,10 @@ function isKeyOfPluginSettings(key: string): key is keyof PluginSettings {
4142
}
4243

4344
const getUserSettings = async () => {
44-
console.log("[DEBUG] getUserSettings - Starting to fetch user settings");
45+
log("[DEBUG] getUserSettings - Starting to fetch user settings");
4546
const possiblePluginSrcSettings =
4647
(await figma.clientStorage.getAsync("userPluginSettings")) ?? {};
47-
console.log(
48+
log(
4849
"[DEBUG] getUserSettings - Raw settings from storage:",
4950
possiblePluginSrcSettings,
5051
);
@@ -65,22 +66,22 @@ const getUserSettings = async () => {
6566
};
6667

6768
userPluginSettings = updatedPluginSrcSettings as PluginSettings;
68-
console.log("[DEBUG] getUserSettings - Final settings:", userPluginSettings);
69+
log("[DEBUG] getUserSettings - Final settings:", userPluginSettings);
6970
return userPluginSettings;
7071
};
7172

7273
const initSettings = async () => {
73-
console.log("[DEBUG] initSettings - Initializing plugin settings");
74+
log("[DEBUG] initSettings - Initializing plugin settings");
7475
await getUserSettings();
7576
postSettingsChanged(userPluginSettings);
76-
console.log("[DEBUG] initSettings - Calling safeRun with settings");
77+
log("[DEBUG] initSettings - Calling safeRun with settings");
7778
safeRun(userPluginSettings);
7879
};
7980

8081
// Used to prevent running from happening again.
8182
let isLoading = false;
8283
const safeRun = async (settings: PluginSettings) => {
83-
console.log(
84+
log(
8485
"[DEBUG] safeRun - Called with isLoading =",
8586
isLoading,
8687
"selection =",
@@ -89,25 +90,25 @@ const safeRun = async (settings: PluginSettings) => {
8990
if (isLoading === false) {
9091
try {
9192
isLoading = true;
92-
console.log("[DEBUG] safeRun - Starting run execution");
93+
log("[DEBUG] safeRun - Starting run execution");
9394
await run(settings);
94-
console.log("[DEBUG] safeRun - Run execution completed");
95+
log("[DEBUG] safeRun - Run execution completed");
9596
// hack to make it not immediately set to false when complete. (executes on next frame)
9697
setTimeout(() => {
97-
console.log("[DEBUG] safeRun - Resetting isLoading to false");
98+
log("[DEBUG] safeRun - Resetting isLoading to false");
9899
isLoading = false;
99100
}, 1);
100101
} catch (e) {
101-
console.log("[DEBUG] safeRun - Error caught in execution");
102+
log("[DEBUG] safeRun - Error caught in execution");
102103
isLoading = false; // Make sure to reset the flag on error
103104
if (e && typeof e === "object" && "message" in e) {
104105
const error = e as Error;
105-
console.log("error: ", error.stack);
106+
log("error: ", error.stack);
106107
figma.ui.postMessage({ type: "error", error: error.message });
107108
} else {
108109
// Handle non-standard errors or unknown error types
109110
const errorMessage = String(e);
110-
console.log("Unknown error: ", errorMessage);
111+
log("Unknown error: ", errorMessage);
111112
figma.ui.postMessage({
112113
type: "error",
113114
error: errorMessage || "Unknown error occurred",
@@ -118,21 +119,21 @@ const safeRun = async (settings: PluginSettings) => {
118119
figma.ui.postMessage({ type: "conversion-complete", success: false });
119120
}
120121
} else {
121-
console.log(
122+
log(
122123
"[DEBUG] safeRun - Skipping execution because isLoading =",
123124
isLoading,
124125
);
125126
}
126127
};
127128

128129
const standardMode = async () => {
129-
console.log("[DEBUG] standardMode - Starting standard mode initialization");
130+
log("[DEBUG] standardMode - Starting standard mode initialization");
130131
figma.showUI(__html__, { width: 450, height: 700, themeColors: true });
131132
await initSettings();
132133

133134
// Listen for selection changes
134135
figma.on("selectionchange", () => {
135-
console.log(
136+
log(
136137
"[DEBUG] selectionchange event - New selection:",
137138
figma.currentPage.selection,
138139
);
@@ -142,7 +143,7 @@ const standardMode = async () => {
142143
// Listen for page changes
143144
figma.loadAllPagesAsync();
144145
figma.on("documentchange", () => {
145-
console.log("[DEBUG] documentchange event triggered");
146+
log("[DEBUG] documentchange event triggered");
146147
// Node: This was causing an infinite load when you try to export a background image from a group that contains children.
147148
// The reason for this is that the code will temporarily hide the children of the group in order to export a clean image
148149
// then restores the visibility of the children. This constitutes a document change so it's restarting the whole conversion.
@@ -151,16 +152,16 @@ const standardMode = async () => {
151152
});
152153

153154
figma.ui.onmessage = async (msg) => {
154-
console.log("[DEBUG] figma.ui.onmessage", msg);
155+
log("[DEBUG] figma.ui.onmessage", msg);
155156

156157
if (msg.type === "pluginSettingWillChange") {
157158
const { key, value } = msg as SettingWillChangeMessage<unknown>;
158-
console.log(`[DEBUG] Setting changed: ${key} = ${value}`);
159+
log(`[DEBUG] Setting changed: ${key} = ${value}`);
159160
(userPluginSettings as any)[key] = value;
160161
figma.clientStorage.setAsync("userPluginSettings", userPluginSettings);
161162
safeRun(userPluginSettings);
162163
} else if (msg.type === "get-selection-json") {
163-
console.log("[DEBUG] get-selection-json message received");
164+
log("[DEBUG] get-selection-json message received");
164165

165166
const nodes = figma.currentPage.selection;
166167
if (nodes.length === 0) {
@@ -187,8 +188,8 @@ const standardMode = async () => {
187188
).document,
188189
),
189190
)) as SceneNode[];
190-
} catch (error) {
191-
console.error("Error exporting JSON:", error);
191+
} catch (err) {
192+
error("Error exporting JSON:", err);
192193
}
193194

194195
try {
@@ -203,13 +204,13 @@ const standardMode = async () => {
203204
};
204205
newNodes.forEach(removeParent);
205206
result.newConversion = newNodes;
206-
} catch (error) {
207-
console.error("Error in new conversion:", error);
207+
} catch (err) {
208+
error("Error in new conversion:", err);
208209
}
209210

210211
const nodeJson = result;
211212

212-
console.log("[DEBUG] Exported node JSON:", nodeJson);
213+
log("[DEBUG] Exported node JSON:", nodeJson);
213214

214215
// Send the JSON data back to the UI
215216
figma.ui.postMessage({
@@ -221,20 +222,20 @@ const standardMode = async () => {
221222
};
222223

223224
const codegenMode = async () => {
224-
console.log("[DEBUG] codegenMode - Starting codegen mode initialization");
225+
log("[DEBUG] codegenMode - Starting codegen mode initialization");
225226
// figma.showUI(__html__, { visible: false });
226227
await getUserSettings();
227228

228229
figma.codegen.on(
229230
"generate",
230231
async ({ language, node }: CodegenEvent): Promise<CodegenResult[]> => {
231-
console.log(
232+
log(
232233
`[DEBUG] codegen.generate - Language: ${language}, Node:`,
233234
node,
234235
);
235236

236237
const convertedSelection = await nodesToJSON([node], userPluginSettings);
237-
console.log(
238+
log(
238239
"[DEBUG] codegen.generate - Converted selection:",
239240
convertedSelection,
240241
);
@@ -406,14 +407,14 @@ const codegenMode = async () => {
406407
switch (figma.mode) {
407408
case "default":
408409
case "inspect":
409-
console.log("[DEBUG] Starting plugin in", figma.mode, "mode");
410+
log("[DEBUG] Starting plugin in", figma.mode, "mode");
410411
standardMode();
411412
break;
412413
case "codegen":
413-
console.log("[DEBUG] Starting plugin in codegen mode");
414+
log("[DEBUG] Starting plugin in codegen mode");
414415
codegenMode();
415416
break;
416417
default:
417-
console.log("[DEBUG] Unknown plugin mode:", figma.mode);
418+
log("[DEBUG] Unknown plugin mode:", figma.mode);
418419
break;
419420
}

apps/plugin/ui-src/App.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
} from "types";
1515
import { postUISettingsChangingMessage } from "./messaging";
1616
import copy from "copy-to-clipboard";
17+
import { log } from "backend/src/common/log";
1718

1819
interface AppState {
1920
code: string;
@@ -48,7 +49,7 @@ export default function App() {
4849
useEffect(() => {
4950
window.onmessage = (event: MessageEvent) => {
5051
const untypedMessage = event.data.pluginMessage as Message;
51-
console.log("[ui] message received:", untypedMessage);
52+
log("[ui] message received:", untypedMessage);
5253

5354
switch (untypedMessage.type) {
5455
case "conversionStart":

packages/backend/src/altNodes/altNodeUtils.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { AltNode } from "types";
22
import { curry } from "../common/curry";
33
import { exportAsyncProxy } from "../common/exportAsyncProxy";
44
import { addWarning } from "../common/commonConversionWarnings";
5+
import { error } from "../common/log";
56

67
export const overrideReadonlyProperty = curry(
78
<T, K extends keyof T>(prop: K, value: any, obj: T): T =>
@@ -54,23 +55,23 @@ export const isSVGNode = (node: SceneNode) => {
5455

5556
export const renderAndAttachSVG = async (node: any) => {
5657
// const nodeName = `${node.type}:${node.id}`;
57-
// console.log(altNode);
58+
// log(altNode);
5859
if (node.canBeFlattened) {
5960
if (node.svg) {
60-
// console.log(`SVG already rendered for ${nodeName}`);
61+
// log(`SVG already rendered for ${nodeName}`);
6162
return node;
6263
}
6364

6465
try {
65-
// console.log(`${nodeName} can be flattened!`);
66+
// log(`${nodeName} can be flattened!`);
6667
const svg = (await exportAsyncProxy<string>(node, {
6768
format: "SVG_STRING",
6869
})) as string;
6970
node.svg = svg;
70-
} catch (error) {
71+
} catch (err) {
7172
addWarning(`Failed rendering SVG for ${node.name}`);
72-
console.error(`Error rendering SVG for ${node.type}:${node.id}`);
73-
console.error(error);
73+
error(`Error rendering SVG for ${node.type}:${node.id}`);
74+
error(err);
7475
}
7576
}
7677
return node;

packages/backend/src/altNodes/jsonNodeConversion.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { PluginSettings } from "types";
33
import { variableToColorName } from "../tailwind/conversionTables";
44
import { HasGeometryTrait, Node, Paint } from "../api_types";
55
import { calculateRectangleFromBoundingBox } from "../common/commonPosition";
6+
import { bench, log } from "../common/log";
67

78
// Performance tracking counters
89
export let getNodeByIdAsyncTime = 0;
@@ -545,9 +546,9 @@ export const nodesToJSON = async (
545546
}),
546547
);
547548

548-
console.log("[debug] initial nodeJson", { ...nodes[0] });
549+
log("[debug] initial nodeJson", { ...nodes[0] });
549550

550-
console.log(
551+
bench(
551552
`[benchmark][inside nodesToJSON] JSON_REST_V1 export: ${Date.now() - exportJsonStart}ms`,
552553
);
553554

@@ -574,7 +575,7 @@ export const nodesToJSON = async (
574575
}
575576
}
576577

577-
console.log(
578+
bench(
578579
`[benchmark][inside nodesToJSON] Process node pairs: ${Date.now() - processNodesStart}ms`,
579580
);
580581

packages/backend/src/altNodes/oldAltConversion.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
assignChildren,
77
} from "./altNodeUtils";
88
import { curry } from "../common/curry";
9+
import { log } from "../common/log";
910

1011
export const isTypeOrGroupOfTypes = curry(
1112
(matchTypes: NodeType[], node: SceneNode): boolean => {
@@ -143,7 +144,7 @@ export const cloneNode = <T extends BaseNode>(
143144
altNode.styledTextSegments = globalTextStyleSegments[node.id];
144145
}
145146

146-
console.log("altnode:", altNode.parent, cloned.parent);
147+
log("altnode:", altNode.parent, cloned.parent);
147148

148149
return altNode;
149150
};

packages/backend/src/code.ts

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
processColorVariablesTime,
2323
resetPerformanceCounters,
2424
} from "./altNodes/jsonNodeConversion";
25+
import { bench, log } from "./common/log";
2526

2627
export const run = async (settings: PluginSettings) => {
2728
resetPerformanceCounters();
@@ -41,14 +42,14 @@ export const run = async (settings: PluginSettings) => {
4142
let convertedSelection: any;
4243
if (useOldPluginVersion2025) {
4344
convertedSelection = oldConvertNodesToAltNodes(selection, null);
44-
console.log("convertedSelection", convertedSelection);
45+
log("convertedSelection", convertedSelection);
4546
} else {
4647
convertedSelection = await nodesToJSON(selection, settings);
47-
console.log(`[benchmark] nodesToJSON: ${Date.now() - nodeToJSONStart}ms`);
48-
console.log("nodeJson", convertedSelection);
48+
bench(`[benchmark] nodesToJSON: ${Date.now() - nodeToJSONStart}ms`);
49+
log("nodeJson", convertedSelection);
4950
}
5051

51-
console.log("[debug] convertedSelection", { ...convertedSelection[0] });
52+
log("[debug] convertedSelection", { ...convertedSelection[0] });
5253

5354
// ignore when nothing was selected
5455
// If the selection was empty, the converted selection will also be empty.
@@ -59,38 +60,39 @@ export const run = async (settings: PluginSettings) => {
5960

6061
const convertToCodeStart = Date.now();
6162
const code = await convertToCode(convertedSelection, settings);
62-
console.log(
63+
bench(
6364
`[benchmark] convertToCode: ${Date.now() - convertToCodeStart}ms`,
6465
);
6566

6667
const generatePreviewStart = Date.now();
6768
const htmlPreview = await generateHTMLPreview(convertedSelection, settings);
68-
console.log(
69+
bench(
6970
`[benchmark] generateHTMLPreview: ${Date.now() - generatePreviewStart}ms`,
7071
);
7172

7273
const colorPanelStart = Date.now();
7374
const colors = retrieveGenericSolidUIColors(framework);
7475
const gradients = retrieveGenericLinearGradients(framework);
75-
console.log(
76+
bench(
7677
`[benchmark] color and gradient panel: ${Date.now() - colorPanelStart}ms`,
7778
);
78-
console.log(
79+
bench(
7980
`[benchmark] total generation time: ${Date.now() - nodeToJSONStart}ms`,
8081
);
82+
console.warn(`${Date.now() - nodeToJSONStart}`)
8183

8284
// Log performance statistics
83-
console.log(
85+
bench(
8486
`[benchmark] getNodeByIdAsync: ${getNodeByIdAsyncTime}ms (${getNodeByIdAsyncCalls} calls, avg: ${(getNodeByIdAsyncTime / getNodeByIdAsyncCalls || 1).toFixed(2)}ms)`,
8587
);
86-
console.log(
88+
bench(
8789
`[benchmark] getStyledTextSegments: ${getStyledTextSegmentsTime}ms (${getStyledTextSegmentsCalls} calls, avg: ${
8890
getStyledTextSegmentsCalls > 0
8991
? (getStyledTextSegmentsTime / getStyledTextSegmentsCalls).toFixed(2)
9092
: 0
9193
}ms)`,
9294
);
93-
console.log(
95+
bench(
9496
`[benchmark] processColorVariables: ${processColorVariablesTime}ms (${processColorVariablesCalls} calls, avg: ${
9597
processColorVariablesCalls > 0
9698
? (processColorVariablesTime / processColorVariablesCalls).toFixed(2)

packages/backend/src/common/exportAsyncProxy.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { postConversionStart } from "../messaging";
2+
// import { log } from "../common/log";
23

34
let isRunning = false;
45

@@ -22,10 +23,10 @@ export const exportAsyncProxy = async <
2223
}
2324

2425
const figmaNode = (await figma.getNodeByIdAsync(node.id)) as ExportMixin;
25-
// console.log("getting figma id for", figmaNode);
26+
// log("getting figma id for", figmaNode);
2627

2728
if (figmaNode.exportAsync === undefined) {
28-
// console.log(node);
29+
// log(node);
2930
throw new TypeError(
3031
"Something went wrong. This node doesn't have an exportAsync() function. Maybe check the type before calling this function.",
3132
);

0 commit comments

Comments
 (0)