Bird
Raised Fist0
Expressframework~10 mins

Structured logging with JSON in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Structured logging with JSON
Start Request
↓
Create Log Object
↓
Add Context Info
↓
Convert to JSON String
↓
Output Log to Console/File
↓
Continue Request Handling
The flow shows how a log entry is created as a JSON object with context, converted to a string, and output for easy reading and analysis.
Execution Sample
Express
app.use((req, res, next) => {
  const logEntry = {
    method: req.method,
    url: req.url,
    timestamp: new Date().toISOString()
  };
  console.log(JSON.stringify(logEntry));
  next();
});
This middleware logs each HTTP request as a JSON string with method, URL, and timestamp.
Execution Table
StepActionlogEntry ObjectJSON.stringify OutputNext Called
1Request received: GET /home{}N/ANo
2Create logEntry with method, url, timestamp{"method":"GET","url":"/home","timestamp":"2024-06-01T12:00:00.000Z"}N/ANo
3Convert logEntry to JSON stringSame as step 2{"method":"GET","url":"/home","timestamp":"2024-06-01T12:00:00.000Z"}No
4Output JSON string to consoleSame as step 2{"method":"GET","url":"/home","timestamp":"2024-06-01T12:00:00.000Z"}No
5Call next() to continue requestSame as step 2Same as step 3Yes
💡 Logging done and next middleware called, request continues
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5
logEntryundefined{"method":"GET","url":"/home","timestamp":"2024-06-01T12:00:00.000Z"}Same as after Step 2Same as after Step 2
Key Moments - 2 Insights
Why do we convert the logEntry object to a JSON string before logging?
Because console.log outputs objects differently in various environments, converting to a JSON string ensures consistent, structured log output as shown in step 3 of the execution_table.
What happens if we forget to call next() in the middleware?
The request will hang and not proceed to the next middleware or route handler, stopping the flow after step 4 in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of logEntry after step 2?
A{"method":"GET","url":"/home","timestamp":"2024-06-01T12:00:00.000Z"}
B{}
Cundefined
Dnull
💡 Hint
Check the 'logEntry Object' column at step 2 in the execution_table
At which step is the JSON string output to the console?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' column describing output in the execution_table
If next() is not called, what happens to the request flow?
ARequest continues normally
BRequest hangs and does not proceed
CRequest is logged twice
DRequest is redirected automatically
💡 Hint
Refer to the key_moments explanation about next() and the exit_note in execution_table
Concept Snapshot
Structured logging with JSON in Express:
- Create a log object with request info
- Convert object to JSON string with JSON.stringify
- Output string to console or file
- Call next() to continue middleware chain
- Ensures logs are easy to parse and consistent
Full Transcript
This example shows how to log HTTP requests in Express using structured JSON. When a request comes in, a log object is created with method, URL, and timestamp. This object is converted to a JSON string using JSON.stringify to ensure consistent output. The JSON string is then printed to the console. Finally, next() is called to continue processing the request. This approach helps keep logs organized and easy to analyze.

Practice

(1/5)
1. What is the main benefit of using structured logging with JSON in an Express app?
easy
A. It makes logs easy to read and parse by both humans and machines.
B. It hides all log messages from users.
C. It automatically fixes bugs in the code.
D. It slows down the server to improve security.

Solution

  1. Step 1: Understand structured logging purpose

    Structured logging formats logs in a clear, consistent way using JSON.
  2. Step 2: Identify benefits of JSON logs

    JSON logs are easy for both humans and machines to read and analyze quickly.
  3. Final Answer:

    It makes logs easy to read and parse by both humans and machines. -> Option A
  4. Quick Check:

    Structured logging = clear, readable logs [OK]
Hint: Think: JSON logs help both people and tools read logs fast [OK]
Common Mistakes:
  • Confusing structured logging with hiding logs
  • Assuming it fixes code bugs automatically
  • Thinking it slows server for security
2. Which of the following is the correct way to log a JSON object with level and message in Express using console.log?
easy
A. console.log('{ level: "info", message: "Server started" }');
B. console.log({ level: 'info', message: 'Server started' });
C. console.log('level: info, message: Server started');
D. console.log(level = 'info', message = 'Server started');

Solution

  1. Step 1: Check JSON object syntax in JavaScript

    JSON objects in JS use curly braces with key-value pairs, keys as strings or identifiers, values as strings or variables.
  2. Step 2: Identify correct console.log usage

    console.log accepts an object directly to print it as JSON-like output, so console.log({ level: 'info', message: 'Server started' }); is correct.
  3. Final Answer:

    console.log({ level: 'info', message: 'Server started' }); -> Option B
  4. Quick Check:

    Use object syntax inside console.log [OK]
Hint: Use curly braces {} for objects inside console.log [OK]
Common Mistakes:
  • Passing JSON as a string instead of object
  • Using incorrect syntax with equals inside console.log
  • Logging plain strings without JSON structure
3. Given the code snippet:
const log = (level, message) => {
  console.log(JSON.stringify({ level, message, timestamp: new Date().toISOString() }));
};
log('error', 'Failed to connect');

What will be the output format?
medium
A. Error: Failed to connect
B. level: error, message: Failed to connect, timestamp: 2024-06-01T12:00:00.000Z
C. [error] Failed to connect at 2024-06-01T12:00:00.000Z
D. {"level":"error","message":"Failed to connect","timestamp":"2024-06-01T12:00:00.000Z"}

Solution

  1. Step 1: Understand JSON.stringify output

    JSON.stringify converts the object into a JSON string with keys and values in double quotes.
  2. Step 2: Analyze the log function output

    The log function prints a JSON string with keys level, message, and timestamp in ISO format.
  3. Final Answer:

    {"level":"error","message":"Failed to connect","timestamp":"2024-06-01T12:00:00.000Z"} -> Option D
  4. Quick Check:

    JSON.stringify outputs JSON string [OK]
Hint: JSON.stringify outputs double-quoted JSON string [OK]
Common Mistakes:
  • Expecting plain text instead of JSON string
  • Confusing JSON string with object literal
  • Ignoring timestamp format
4. You wrote this code to log JSON in Express:
console.log(JSON.stringify(level: 'info', message: 'Started'));

What is the error and how to fix it?
medium
A. TypeError because console.log cannot print JSON strings; fix by removing JSON.stringify.
B. No error; code logs JSON correctly.
C. SyntaxError due to incorrect JSON.stringify argument; fix by passing an object inside curly braces.
D. ReferenceError because level and message are undefined variables.

Solution

  1. Step 1: Identify JSON.stringify argument syntax

    JSON.stringify expects a single object or value; here, the argument uses invalid syntax without braces.
  2. Step 2: Correct the argument to an object

    Wrap the key-value pairs inside curly braces to form a valid object: { level: 'info', message: 'Started' }.
  3. Final Answer:

    SyntaxError due to incorrect JSON.stringify argument; fix by passing an object inside curly braces. -> Option C
  4. Quick Check:

    JSON.stringify needs an object argument [OK]
Hint: Always pass an object inside {} to JSON.stringify [OK]
Common Mistakes:
  • Passing key-value pairs without braces
  • Assuming JSON.stringify accepts multiple arguments
  • Ignoring syntax errors in object literals
5. You want to add structured logging in Express that includes level, message, timestamp, and requestId from middleware. Which code snippet correctly logs this info?
hard
A. app.use((req, res, next) => { console.log(JSON.stringify({ level: 'info', message: 'Request received', timestamp: new Date().toISOString(), requestId: req.id })); next(); });
B. app.use((req, res, next) => { console.log({ level: 'info', message: 'Request received', timestamp: new Date(), requestId: req.id }); next(); });
C. app.use((req, res, next) => { console.log('Request received at ' + new Date() + ' with id ' + req.id); next(); });
D. app.use((req, res, next) => { console.log(JSON.stringify(level: 'info', message: 'Request received', timestamp: new Date().toISOString(), requestId: req.id)); next(); });

Solution

  1. Step 1: Check correct JSON object syntax inside JSON.stringify

    app.use((req, res, next) => { console.log(JSON.stringify({ level: 'info', message: 'Request received', timestamp: new Date().toISOString(), requestId: req.id })); next(); }); correctly passes an object with keys and values inside curly braces to JSON.stringify.
  2. Step 2: Verify inclusion of all required fields and middleware usage

    app.use((req, res, next) => { console.log(JSON.stringify({ level: 'info', message: 'Request received', timestamp: new Date().toISOString(), requestId: req.id })); next(); }); includes level, message, timestamp (ISO string), and requestId from req.id, then calls next() properly.
  3. Final Answer:

    app.use((req, res, next) => { console.log(JSON.stringify({ level: 'info', message: 'Request received', timestamp: new Date().toISOString(), requestId: req.id })); next(); }); -> Option A
  4. Quick Check:

    Middleware logs JSON object with all fields [OK]
Hint: Use JSON.stringify with object including all fields inside middleware [OK]
Common Mistakes:
  • Passing invalid syntax to JSON.stringify
  • Logging plain strings instead of JSON
  • Forgetting to call next() in middleware
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard