1. function serializeLogStream(logStream) {
  2. try {
  3. // Attempt to serialize using JSON.stringify
  4. return JSON.stringify(logStream, null, 2); // Pretty print with 2 spaces
  5. } catch (error) {
  6. // Fallback: Convert to a string representation if JSON serialization fails
  7. console.error("JSON serialization failed. Using string fallback.", error);
  8. return String(logStream);
  9. }
  10. }
  11. // Example Usage (for testing)
  12. const logData = {
  13. timestamp: Date.now(),
  14. level: "info",
  15. message: "This is a test log message.",
  16. data: {
  17. user_id: 123,
  18. event: "page_view"
  19. }
  20. };
  21. const serializedString = serializeLogStream(logData);
  22. console.log(serializedString);
  23. //Example with non-serializable object
  24. const logData2 = {
  25. timestamp: Date.now(),
  26. level: "info",
  27. message: "This is a test log message.",
  28. functionName: function(){console.log("hello")}
  29. }
  30. const serializedString2 = serializeLogStream(logData2);
  31. console.log(serializedString2);

Add your comment