Skip to content

Commit

Permalink
pretty print raw JSON in logs (#2260)
Browse files Browse the repository at this point in the history
* pretty print raw JSON in logs

* add CL

* optimize, add types

* forget trim, do less. do less.

* thank you aicha hassen
  • Loading branch information
taylordowns2000 authored Jul 5, 2024
1 parent 25e1616 commit df3cdb1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 29 additions & 2 deletions assets/js/log-viewer/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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 = () => {
Expand Down

0 comments on commit df3cdb1

Please sign in to comment.