Introduction to treport-logger
The treport-logger
library is a powerful and flexible logging tool for modern JavaScript and Node.js applications. It offers a wide range of features that make logging, debugging, and monitoring easier. In this guide, we will dive deep into its API with useful code snippets and examples.
Getting Started
First, you need to install treport-logger
:
npm install treport-logger
Now, let’s explore some of the basic functionalities:
Creating a Basic Logger
const logger = require('treport-logger');
logger.info('Information message'); logger.warn('Warning message'); logger.error('Error message');
Advanced Configuration
const config = {
level: 'debug',
transports: [
new logger.transports.Console(),
new logger.transports.File({ filename: 'app.log' })
]
}; const advancedLogger = logger.createLogger(config);
advancedLogger.debug('Debug message');
Logging HTTP Requests
const http = require('http'); const middlewareLogger = require('treport-logger').createLogger(config);
const server = http.createServer((req, res) => {
middlewareLogger.info(`${req.method} ${req.url}`);
res.end('Hello World');
});
server.listen(3000, () => {
middlewareLogger.info('Server is listening on port 3000');
});
Custom Transports
class CustomTransport {
log(info, callback) {
// custom logging logic here
callback();
}
}
const customLogger = logger.createLogger({
transports: [new CustomTransport()]
});
customLogger.info('Using custom transport');
Building an Application Using treport-logger
Let’s build a small application to demonstrate how to integrate treport-logger
:
const express = require('express'); const app = express(); const logger = require('treport-logger').createLogger(config);
app.use((req, res, next) => {
logger.info(`Received ${req.method} request for ${req.url}`);
next();
});
app.get('/', (req, res) => {
logger.debug('Handling GET /');
res.send('Hello, World!');
});
app.listen(4000, () => {
logger.info('App running on port 4000');
});
With this setup, we can easily see incoming requests and simple operations happening within our application.
Hash: f9f4f9199f9e6beb92331317c09b91555bce60f129c029baeee1ff56380a98ad