Node.js API Monitor: How to Track API Logs for Free
October 18, 2024
Learn how to monitor API logs in Node.js for free. Store and search requests easily, with additional features to enhance your API monitoring.
Software Dev
Trending
Latest in tech
Introduction
As a Node.js developer, I often want to see the data being sent to my server (especially webhooks), the data I send back, the response times, etc. However, most tools that provide this functionality are expensive. To solve this problem, I created an NPM package that allows me to view my API logs, store them in my MongoDB database, and add other team members. It's called Node_API_logs and currently works only with Express.js apps.
How to install
npm i node-api-logs
Yarn add node-api-logs
How to setup
must be using Express.js
Required
- MongoDB Uri
- Set node_api_logger_jwtSecret on your .env else the general string will be used to generate token.
- beginsWith : Imagine you want to avoid saving logs for requests that begins with /api/auth, you can add it to this array.
- specifics: This is to avoid a specific url . For example : /api/health. If this is added to the "specific" array, all requests to that endpoint won't be saved.
What it looks like
Visit url : http://localhost:${port}/logs/login
- Login route (/login) : Input creds and generate token
- Logs route (/) : see logs, filter by endpoint, time ,date etc.
- Log details (/logs/${id}) : See log details.
Add new member
open MongoDB -> add new document -> add email -> save
user logins (password is set automatically).
Change password
- Use Bcrypt (Longer method: your choice) .
- Just delete password from Db and re-login (works like the add user password).
Code Sample
import express, { Application, Request, Response } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import dotenv from 'dotenv';
import expressFileUpload from 'express-fileupload';
import path from 'path';
import { createExpressLogger } from 'node-api-logs';
// configurations
dotenv.config();
import './config/database';
import './config/redis';
import AppRoutes from './modules/app/app.route';
import { formatReq } from './middlewares/helpers.middleware';
import logger from './config/logger';
import morgan from 'morgan';
import morganMiddleware from './middlewares/morgan.middleware';
// Boot express
const app: Application = express();
const port = process.env.PORT || 3000;
const base: string = process.env.base_url ?? '/staging/api/v1';
// middlewares
app.use(cors());
app.use(helmet());
app.use(expressFileUpload({ createParentPath: true, useTempFiles: true }));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use('/docs', express.static(path.join(__dirname, 'docs')));
app.use(formatReq);
app.use(morganMiddleware);
createExpressLogger({ app: app, mongoUri: process.env.MONGO_TEST_URI || process.env.MONGO_URI || '' });
// Application routing
app.get('/', (req: Request, res: Response) => {
res.status(200).send({ data: 'BACKEND Application' });
});
app.use(base, AppRoutes);
// Start server
app.listen(port, () => logger.info(`Server is listening on port ${port}!`));
export default app;
// Handle unhandled promise rejections and exceptions
process.on('unhandledRejection', (err: any) => {
logger.error('Unhandled Rejection', err);
});
process.on('uncaughtException', (err: any) => {
logger.error(err.message, err);
});
Contribute
Visit Github, fork, work (cook), create issue, create PR and get merged.
Conclusion
Star, comment, leave feedbacks (other Node.js framework you'll love to make available) and updates you think are necessary. Thanks for reading.
See moreLeave a Reply
Your email address will not be published.
Required fields are marked*
Comment *
Name*
Email*