diff --git a/CHANGELOG.md b/CHANGELOG.md index 537e94b235..77b6f2b2ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ and this project adheres to ### Changed +- When the entire log string is a valid JSON object, pretty print it with a + standard `JSON.stringify(str, null, 2)` but if it's something else then let + the user do whatever they want (e.g., if you write + `console.log('some', 'cool', state.data)` we won't mess with it.) + [#2260](https://github.com/OpenFn/lightning/pull/2260) + ### Fixed ## [v2.7.3] - 2024-07-05 diff --git a/assets/js/log-viewer/store.ts b/assets/js/log-viewer/store.ts index 151dc1bcef..ab0683ed2d 100644 --- a/assets/js/log-viewer/store.ts +++ b/assets/js/log-viewer/store.ts @@ -28,7 +28,9 @@ function findSelectedRanges(logs: LogLine[], stepId: string | undefined) { }>( ({ ranges, marker }, log) => { // Get the number of newlines in the message, used to determine the end index. - const newLineCount = [...log.message.matchAll(/\n/g)].length; + const newLineCount = [...possiblyPrettify(log.message).matchAll(/\n/g)] + .length; + const nextMarker = marker + 1 + newLineCount; if (log.step_id !== stepId) { @@ -65,8 +67,33 @@ function coerceLogs(logs: LogLine[]): LogLine[] { })); } +function isProbablyJSON(str: string) { + // Check if the string starts with '{' or '[' and ends with '}' or ']' + return ( + (str.startsWith('{') && str.endsWith('}')) || + (str.startsWith('[') && str.endsWith(']')) + ); +} + +function tryPrettyJSON(str: string) { + try { + const jsonObj = JSON.parse(str); + return JSON.stringify(jsonObj, null, 2); + } catch { + return str; + } +} + +function possiblyPrettify(str: string | string) { + if (isProbablyJSON(str)) { + return tryPrettyJSON(str); + } + return str; +} + function formatLogLine(log: LogLine) { - return `${log.source} ${log.message}`; + const { source, message } = log; + return `${source} ${possiblyPrettify(message)}`; } export const createLogStore = () => {