0
0
Node.jsframework~10 mins

Logging with structured formats in Node.js - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Logging with structured formats
Start Application
Create Logger
Generate Log Message
Format Log as JSON
Output to Console/File
Log Stored in Structured Format
The app starts, creates a logger, formats messages as JSON, and outputs them for easy reading and searching.
Execution Sample
Node.js
const log = (level, message, meta = {}) => {
  const entry = { level, message, timestamp: new Date().toISOString(), ...meta };
  console.log(JSON.stringify(entry));
};

log('info', 'User login', { userId: 123 });
This code logs a message with level, text, timestamp, and extra info as a JSON string.
Execution Table
StepActionInputOutputNotes
1Call log functionlevel='info', message='User login', meta={userId:123}entry object createdCombines inputs into one object with timestamp
2Create timestampnew Date().toISOString()"2024-06-01T12:00:00.000Z"Current time in ISO format
3Merge all fieldslevel, message, timestamp, meta{"level":"info","message":"User login","timestamp":"2024-06-01T12:00:00.000Z","userId":123}Final structured log entry
4Convert to JSON stringentry object"{\"level\":\"info\",\"message\":\"User login\",\"timestamp\":\"2024-06-01T12:00:00.000Z\",\"userId\":123}"Ready for output
5Output to consoleJSON stringPrinted JSON log lineVisible in console or log file
6End--Logging complete
💡 Logging function completes after outputting the structured JSON log line
Variable Tracker
VariableStartAfter Step 1After Step 3Final
levelundefinedinfoinfoinfo
messageundefinedUser loginUser loginUser login
metaundefined{userId:123}{userId:123}{userId:123}
timestampundefinedundefined2024-06-01T12:00:00.000Z2024-06-01T12:00:00.000Z
entryundefinedpartial object{"level":"info","message":"User login","timestamp":"2024-06-01T12:00:00.000Z","userId":123}final object
Key Moments - 3 Insights
Why do we use JSON.stringify before outputting the log?
Because the log entry is an object, and console.log prints objects differently. JSON.stringify converts it to a single-line string that is easy to read and parse, as shown in step 4 of the execution_table.
What is the purpose of the timestamp in the log entry?
The timestamp shows when the log happened. It helps track events over time. In the execution_table, step 2 creates this timestamp in a standard ISO format.
Why do we merge meta fields into the main log entry?
Merging meta fields adds extra details to the log without losing the main message or level. This is shown in step 3 where meta is combined with level, message, and timestamp.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what does the 'entry' object contain?
AJust the timestamp field
BOnly level and message fields
CLevel, message, timestamp, and meta fields merged
DA plain string message
💡 Hint
Check the 'Output' column in step 3 of the execution_table for the full object contents.
At which step is the log entry converted into a JSON string?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look at the 'Action' column for the step mentioning JSON string conversion.
If we remove the meta parameter, what changes in the variable_tracker for 'entry'?
AThe level field will be missing
BThe entry object will not have meta fields
CThe timestamp will be missing
DThe message field will be empty
💡 Hint
Refer to the 'meta' and 'entry' rows in variable_tracker to see how meta affects the final object.
Concept Snapshot
Logging with structured formats in Node.js:
- Create a log object with level, message, timestamp, and extra data
- Use JSON.stringify to convert the object to a string
- Output the JSON string to console or file
- Structured logs are easy to search and analyze
- Always include timestamp for event tracking
Full Transcript
This visual execution shows how to log messages in Node.js using structured JSON format. The process starts by calling a log function with level, message, and optional meta data. A timestamp is created in ISO format. All fields are merged into one object. Then JSON.stringify converts this object into a string. Finally, the string is printed to the console. This method helps keep logs consistent and easy to read or parse by tools. Key points include why JSON.stringify is needed, the role of timestamp, and how meta data is merged into the log entry.