📖 Scenario: You are building a simple Express server. To help with debugging and monitoring, you want to log requests in a structured JSON format. This makes logs easier to read and analyze by tools.
🎯 Goal: Create an Express server that logs each incoming request as a JSON object with keys for method, url, and timestamp.
📋 What You'll Learn
Create an Express app instance
Add a middleware to log requests in JSON format
Log method, url, and timestamp in ISO format
Start the server on port 3000
Print the JSON log to the console for each request
💡 Why This Matters
🌍 Real World
Structured JSON logs help developers and operations teams quickly understand server activity and diagnose issues by parsing logs with tools.
💼 Career
Logging is a key skill for backend developers and DevOps engineers to monitor and troubleshoot applications in production.
Progress0 / 4 steps
1
Setup Express app
Create a variable called express that requires the 'express' module. Then create a variable called app by calling express().
Express
Hint
Use require('express') to import Express, then call it as a function to create the app.
2
Add JSON logging middleware
Add a middleware to app using app.use. The middleware should be a function with parameters req, res, and next. Inside it, create a variable logEntry that is an object with keys method (from req.method), url (from req.url), and timestamp (current time in ISO string format). Then log logEntry as a JSON string using console.log(JSON.stringify(logEntry)). Finally, call next().
Express
Hint
The middleware function logs the request details as JSON and then calls next() to continue.
3
Add a simple route
Add a GET route on / to app using app.get. The route handler should send the text 'Hello World' as the response.
Express
Hint
Use app.get with path '/' and send 'Hello World' as response.
4
Start the server
Start the Express server by calling app.listen on port 3000. Add a callback function that prints 'Server running on port 3000' to the console.
Express
Hint
Use app.listen(3000, () => { console.log(...) }) to start the server.
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
Step 1: Understand structured logging purpose
Structured logging formats logs in a clear, consistent way using JSON.
Step 2: Identify benefits of JSON logs
JSON logs are easy for both humans and machines to read and analyze quickly.
Final Answer:
It makes logs easy to read and parse by both humans and machines. -> Option A
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
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.
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.
Final Answer:
console.log({ level: 'info', message: 'Server started' }); -> Option B
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
Step 1: Understand JSON.stringify output
JSON.stringify converts the object into a JSON string with keys and values in double quotes.
Step 2: Analyze the log function output
The log function prints a JSON string with keys level, message, and timestamp in ISO format.
Final Answer:
{"level":"error","message":"Failed to connect","timestamp":"2024-06-01T12:00:00.000Z"} -> Option D
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();
});