Last active
July 5, 2023 21:57
-
-
Save epeters3/47ac165a3077053bf5e410a580a75973 to your computer and use it in GitHub Desktop.
CloudWatch Log Events With Metadata
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type JSONValue = | |
| string | |
| number | |
| boolean | |
| { [x: string]: JSONValue } | |
| Array<JSONValue>; | |
/** | |
* A CloudWatch Logs type. | |
*/ | |
type InputLogEvent = { | |
timestamp: number; | |
message: string; | |
}; | |
type LogEvent = { | |
/** | |
* In case we want to store other types of events in the future, like e.g. "completedStage". | |
*/ | |
type: 'logEntry'; | |
/** | |
* The time when the log event occurred, expressed as milliseconds since the Unix epoch. | |
*/ | |
timestamp: number; | |
/** | |
* The actual log event body. Can be arbitrary JSON. | |
*/ | |
payload: JSONValue; | |
/** | |
* The stage or component of the pipeline that produced this log entry. | |
*/ | |
stage: string; | |
}; | |
const isValidJson = (s: string) => { | |
try { | |
JSON.parse(s); | |
return true; | |
} catch { | |
return false; | |
} | |
}; | |
const createLogEvent = ( | |
{ timestamp, message }: InputLogEvent, | |
stage: string, | |
): LogEvent => { | |
const payload = isValidJson(message) ? JSON.parse(message) : message; | |
return { type: 'logEntry', timestamp, payload, stage }; | |
}; | |
describe('json log statements', () => { | |
it('can represent log events correctly', () => { | |
const testCases: string[] = [ | |
'{"foo": "bar", "msg": "I am a valid JSON string."}', | |
'"I am not a valid JSON string but I use "reserved [JSON characters}.', | |
'I am a plain string.', | |
]; | |
testCases.forEach((testCase) => { | |
const event = createLogEvent( | |
{ timestamp: Date.now(), message: testCase }, | |
'train-001', | |
); | |
// The event must be stringifiable and parseable. | |
const stringified = JSON.stringify(event); | |
const parsed = JSON.parse(stringified); | |
console.log( | |
'---------------------------------------------------------------', | |
); | |
console.log(stringified); | |
console.log(parsed); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment