Copy the code
node index.js > hello.log 2> error.log
Terminal screenshot showing error output in a different file
When to journal?
Now that we know a bit more about the underlying technical side of logging, let's talk a bit about the different use cases in which you might want to log something. Typically, these use cases fall into one of the philippines mobile number example following categories:
Quickly debug unexpected behavior during development
Logging from the browser for analysis or diagnostic purposes
Logs that allow your server application to log incoming requests, as well as any failures
Optional debug logs for your library to help the user troubleshoot issues
Output from your command line interface to print progress, confirmation messages, or errors
In this post, we will ignore the first two to better focus on the three Node.js-based examples.
Your Server Application Logs
There are several reasons why you might want to log things on your server. Logging incoming requests, for example, allows you to extract statistics such as how many 404 errors users are encountering, what they might be, or what User-Agent is being used. Similarly, you want to know when things went wrong, and why.
If you want to try the different methods that follow in this section of the post, make sure to create a new project directory. Create a file index.js in the project directory for the code we will be using and run the following commands to initialize a project and install express :
JavaScript
Copy the code
npm init -y
npm install express
Now let's set up a server with some middleware that will simply log every request for you using console.log. Put the following in the file index.js :
JavaScript
Copy the code
const express = require('express');
const PORT = process.env.PORT || 3000;
const app = express();
app.use((req, res, next) => {
console.log('%O', req);
next();
});
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(PORT, () => {
console.log('Server running on port %d', PORT);
});
We use here console.log('%O', req) to log the entire object. console.log uses under the hood util.format that supports other placeholders besides '%O'. You can read more about it from the Node.js documentation .
If you use node index.js to run your server and go to http ://localhost:3000 , you will notice a lot of information that we don't really need.
Terminal screenshot showing output with too many results for request object
If you replace it with console.log('%s', req) to not print the entire object, we won't get much information either.
Terminal screenshot printing "[object Object]" repeatedly
We could write our own log function to print only what we are interested in, but let's start by backtracking and talking about what we are usually interested in. Although our main focus is on the message, we often actually need additional information. Information such as:
Your Server Application Logs
-
- Posts: 10
- Joined: Sun Dec 22, 2024 5:36 am