Querying Logs

If you’re logging to a database or an external service, querying logs can be useful. For instance, with MongoDB and winston-mongodb, you can query logs like this:

const winston = require('winston');
require('winston-mongodb');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
), transports: [
new winston.transports.MongoDB({
  db: 'mongodb://localhost/logs',
  collection: 'log',
  level: 'info'
})
] }); // Querying logs from MongoDB const MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost/logs', function (err, client) { if (err) throw err; const db = client.db('logs'); const collection = db.collection('log'); collection.find({ level: 'info' }).toArray(function (err, docs) {
if (err) throw err;
console.log(docs);
client.close();
}); });

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *