Bird
Raised Fist0
Expressframework~20 mins

Structured logging with JSON in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Structured Logging Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
1:30remaining
Output of JSON structured log in Express middleware
Consider this Express middleware that logs request info as JSON. What is the output when a GET request to '/test' with header 'User-Agent: curl/7.68.0' is received?
Express
app.use((req, res, next) => {
  const logEntry = {
    method: req.method,
    url: req.url,
    userAgent: req.headers['user-agent']
  };
  console.log(JSON.stringify(logEntry));
  next();
});
A{"method":"GET","url":"/test"}
B{method: GET, url: /test, userAgent: curl/7.68.0}
C{"method":"GET","url":"/test","userAgent":"curl/7.68.0"}
DSyntaxError: Unexpected token m in JSON at position 1
Attempts:
2 left
💡 Hint
Remember JSON.stringify converts an object to a JSON string with double quotes.
❓ Configuration
intermediate
1:30remaining
Correct JSON logging configuration for Winston in Express
Which Winston logger configuration correctly outputs logs in JSON format with timestamp and level fields?
Aconst logger = winston.createLogger({ format: winston.format.printf(info => `${info.level}: ${info.message}`), transports: [new winston.transports.Console()] });
Bconst logger = winston.createLogger({ format: winston.format.json(), transports: [new winston.transports.Console()] });
Cconst logger = winston.createLogger({ format: winston.format.simple(), transports: [new winston.transports.Console()] });
Dconst logger = winston.createLogger({ format: winston.format.colorize(), transports: [new winston.transports.Console()] });
Attempts:
2 left
💡 Hint
JSON format outputs structured logs as JSON objects.
❓ Troubleshoot
advanced
2:00remaining
Why does JSON.parse fail on logged Express request object?
You try to log the entire Express request object as JSON with JSON.stringify(req) and then parse it back with JSON.parse. It throws an error. Why?
Express
const jsonString = JSON.stringify(req);
const obj = JSON.parse(jsonString);
AJSON.stringify automatically removes all functions, so parse fails due to missing methods.
BJSON.parse cannot parse strings longer than 1KB.
CExpress request object is a string, so JSON.stringify returns the same string causing parse error.
DExpress request object contains circular references causing JSON.stringify to fail silently or produce incomplete output.
Attempts:
2 left
💡 Hint
Think about what kind of data structures JSON.stringify can handle.
🔀 Workflow
advanced
2:00remaining
Best workflow to add structured JSON logging with request IDs in Express
You want to add a unique request ID to every log entry in Express using structured JSON logging. Which workflow correctly achieves this?
AUse middleware to generate a UUID, attach it to req.id, then use a custom logger that includes req.id in every log entry.
BGenerate UUID in each route handler and pass it manually to logger calls only in those handlers.
CUse global variable to store current request ID and read it in logger calls.
DAdd request ID only in error handling middleware, ignoring normal requests.
Attempts:
2 left
💡 Hint
Think about how to consistently add request ID to all logs for a request.
✅ Best Practice
expert
2:30remaining
Which logging practice improves observability in distributed Express apps?
In a distributed Express app with multiple services, which logging practice best improves observability and troubleshooting?
AUse structured JSON logs with consistent fields including trace IDs propagated across services.
BLog only error messages as plain text to reduce log size.
CUse different log formats per service to optimize for local readability.
DDisable logging in production to improve performance.
Attempts:
2 left
💡 Hint
Think about how to correlate logs across multiple services.

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