📖 Scenario: You are building a simple Node.js application that logs user actions. To make logs easy to read and analyze, you will use structured JSON format for logging.
🎯 Goal: Create a Node.js script that logs user actions as JSON objects with clear keys for user, action, and timestamp.
📋 What You'll Learn
Create an object representing a user action with keys user, action, and timestamp
Add a configuration variable for the current time in ISO format
Use a function to create a structured log object combining user, action, and timestamp
Print the structured log as a JSON string
💡 Why This Matters
🌍 Real World
Structured logging helps teams quickly find and analyze logs in production systems, improving troubleshooting and monitoring.
💼 Career
Understanding structured logging is essential for DevOps roles to maintain reliable and observable applications.
Progress0 / 4 steps
1
Create the user action object
Create a constant object called userAction with these exact keys and values: user set to "alice", action set to "login", and timestamp set to an empty string "".
Create a constant called currentTime and set it to the current date and time in ISO string format using new Date().toISOString().
Node.js
Hint
Use const currentTime = new Date().toISOString(); to get the current time in ISO format.
3
Create a function to build structured log
Write a function called buildLog that takes user, action, and timestamp as parameters and returns an object with these keys and values. Then update userAction.timestamp by calling buildLog with userAction.user, userAction.action, and currentTime, and assign the returned object's timestamp to userAction.timestamp.
Node.js
Hint
Define buildLog to return an object with keys user, action, and timestamp. Then update userAction.timestamp using this function.
4
Print the structured log as JSON
Use console.log to print the userAction object as a JSON string using JSON.stringify(userAction).
Node.js
Hint
Use console.log(JSON.stringify(userAction)) to print the object as JSON.
Practice
(1/5)
1. What is the main benefit of using structured logging in Node.js applications?
easy
A. Logs are stored as plain text without any format.
B. Logs are only saved in memory and not written to files.
C. Logs are encrypted automatically for security.
D. Logs are saved in a clear, organized JSON format for easy reading and processing.
Solution
Step 1: Understand structured logging
Structured logging means saving logs in a format like JSON that is easy to read and parse.
Step 2: Identify the benefit
This format helps both humans and tools quickly understand log data.
Final Answer:
Logs are saved in a clear, organized JSON format for easy reading and processing. -> Option D
Quick Check:
Structured logging = JSON format logs [OK]
Hint: Structured logs use JSON for clarity and easy parsing [OK]
Common Mistakes:
Thinking logs are encrypted by default
Confusing plain text logs with structured logs
Assuming logs are only stored in memory
2. Which of the following is the correct way to create a logger using the pino library in Node.js?
easy
A. const logger = require('pino')();
B. const logger = new pino.Logger();
C. const logger = pino.create();
D. const logger = require('pino').createLogger();
Solution
Step 1: Recall pino import syntax
The pino library is imported using require('pino'), which returns a function.
Step 2: Create logger instance
Calling this function with () creates the logger instance: require('pino')()
Final Answer:
const logger = require('pino')(); -> Option A
Quick Check:
pino logger created by calling require('pino')() [OK]
Hint: Use require('pino')() to create logger instance [OK]
Common Mistakes:
Using createLogger() which does not exist
Trying to use new keyword with pino
Calling pino.create() which is invalid
3. What will be the output of the following Node.js code using pino?
A. The order of arguments is incorrect; the object should come first.
B. Missing semicolon after require statement.
C. pino() must be called with configuration object.
D. logger.info cannot accept two arguments.
Solution
Step 1: Check pino.info argument order
pino expects the first argument as an object with extra data, second as message string.
Step 2: Analyze given code
The code passes message string first, then object, which is reversed and causes wrong output.
Final Answer:
The order of arguments is incorrect; the object should come first. -> Option A
Quick Check:
pino.info(object, message) argument order [OK]
Hint: Pass object first, then message string to logger.info [OK]
Common Mistakes:
Swapping message and object arguments
Thinking semicolon is mandatory for correctness
Assuming pino() needs config always
5. You want to log user events with structured logs including user ID, event type, and timestamp using pino. Which code snippet correctly logs this data ensuring timestamp is included in the JSON output?
hard
A. logger.info({ userId: 123, event: 'click' }, 'User event at ' + new Date());
C. logger.info({ userId: 123, event: 'click', time: new Date().toISOString() }, 'User event');
D. logger.info({ userId: 123, event: 'click', timestamp: Date.now() });
Solution
Step 1: Ensure correct argument order and timestamp format
pino expects object first, then message string. Timestamp should be ISO string for readability.
Step 2: Check each option
logger.info({ userId: 123, event: 'click', time: new Date().toISOString() }, 'User event'); passes object with userId, event, and ISO timestamp, then message string. This is correct.
Final Answer:
logger.info({ userId: 123, event: 'click', time: new Date().toISOString() }, 'User event'); -> Option C
Quick Check:
Object first with ISO timestamp, then message [OK]
Hint: Pass object with ISO timestamp first, then message string [OK]
Common Mistakes:
Swapping message and object arguments
Using Date.now() without formatting
Concatenating message and timestamp in string
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.