Welcome to Chain Logger
Chain Logger is a powerful logging library designed to provide a flexible and comprehensive logging solution for your applications. Here’s an introduction to Chain Logger and dozens of useful API explanations with code snippets that can help you leverage its capabilities to the fullest.
Getting Started
To start using Chain Logger, install it via npm:
npm install chain-logger
Basic Usage
Create a simple logger:
const { Logger } = require('chain-logger'); const logger = new Logger(); logger.log('info', 'Hello, world!');
Advanced Usage
Customize your logging format:
const { Logger, transports } = require('chain-logger'); const logger = new Logger({
format: 'json',
transports: [
new transports.Console(),
new transports.File({ filename: 'combined.log' })
]
});
Logging Levels
Adjust logging levels:
logger.setLevel('debug'); logger.log('debug', 'Debugging information'); logger.log('error', 'Error message');
Log Rotation
Implement log rotation:
const { Logger, transports } = require('chain-logger'); const logger = new Logger({
transports: [
new transports.File({
filename: 'logs/app.log',
rotation: { maxFiles: 5, maxSize: '1m' }
})
]
});
HTTP Logging
Log HTTP requests:
const express = require('express'); const { Logger, transports } = require('chain-logger'); const app = express(); const logger = new Logger({
transports: [new transports.Console()]
});
app.use((req, res, next) => {
logger.log('info', `HTTP ${req.method} ${req.url}`);
next();
});
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(3000, () => {
logger.log('info', 'Server is running on port 3000');
});
Structured Logging
Log structured data:
const logger = new Logger(); logger.log('info', 'User logged in', { userId: 123, role: 'admin' });
Asynchronous Logging
Handle asynchronous logging:
const logger = new Logger(); async function fetchData() {
try {
const data = await getDataFromAPI();
logger.log('info', 'Data fetched successfully', data);
} catch (error) {
logger.log('error', 'Failed to fetch data', error);
}
}
Example Application
Here is a complete example application using some of the APIs introduced above:
const express = require('express'); const { Logger, transports } = require('chain-logger'); const app = express(); const logger = new Logger({
transports: [
new transports.Console(),
new transports.File({ filename: 'logs/app.log' })
]
});
app.use((req, res, next) => {
logger.log('info', `HTTP ${req.method} ${req.url}`);
next();
});
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.get('/error', (req, res) => {
res.status(500).send('Something went wrong');
logger.log('error', 'Error occurred on /error endpoint');
});
app.listen(3000, () => {
logger.log('info', 'Server is running on port 3000');
});
With Chain Logger, you can build powerful and efficient logging into your applications. Start enhancing your logging capabilities today!
Hash: 5ab745dab3f9043261e888616b52384a6fe31dcb3488a08964841ba920c5adc5