Node.js REST Service Logging - app.js
Fri Apr 14 2023 10:44:57 GMT+0000 (Coordinated Universal Time)
Saved by
@mindplumber
#javascript
#nodejs
// app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const createLogger = require('./createLogger');
const adminRoutes = require('./adminRoutes');
const useRoutes = require('./useRoutes');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Initialize the logger
const logger = createLogger();
// Add routes for the "admin" category
app.use('/admin/info', adminRoutes.info(logger));
app.use('/admin/warn', adminRoutes.warn(logger));
app.use('/admin/error', adminRoutes.error(logger));
// Add routes for the "use" category
app.use('/use/info', useRoutes.info(logger));
app.use('/use/warn', useRoutes.warn(logger));
app.use('/use/error', useRoutes.error(logger));
// Endpoint for adding a new category and routes dynamically
app.post('/addCategory', (req, res) => {
const category = req.body.category;
const routes = req.body.routes;
// Create a new logger for the category
const categoryLogger = createLogger(category);
// Add routes for the category
for (const route of routes) {
app.use(`/${category}/${route}/info`, (req, res) => {
categoryLogger.info({ message: req.query.message });
res.send('Logged info message');
});
app.use(`/${category}/${route}/warn`, (req, res) => {
categoryLogger.warn({ message: req.query.message });
res.send('Logged warning message');
});
app.use(`/${category}/${route}/error`, (req, res) => {
categoryLogger.error({ message: req.query.message });
res.send('Logged error message');
});
}
res.send(`Added category ${category} with routes ${routes.join(', ')}`);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
content_copyCOPY
With this code, you can send a POST request to the `/addCategory` endpoint with the `category` and `routes` parameters in the request body to dynamically add a new logging category and corresponding routes to the application. The `routes` parameter should be an array of strings representing the new routes to be added for the category.
Comments