Reputation: 2387
I am using the winston library: https://github.com/flatiron/winston Attempting to store data to the mongodb database with: https://github.com/indexzero/winston-mongodb
to insert the data I use:
var MongoDB = require('winston-mongodb').MongoDB;
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winston.transports.MongoDB)({ host: ip, db: 'caribcultivate', collection: 'log', level: 'info'})
], exceptionHandlers: [ new winston.transports.Console() ]
});
logger.log('info', "Running logs "+ d);
logger.info("Drive: "+ (new Date(d)).toDateString());
However when I try to query the data using:
winston.query(options, function (err, results) {
if (err) {console.log(err);}
console.log(results);
});
I get:
{}
It works for the Console correctly, and I am using the database in other parts of the application with the Mongoose library.
Upvotes: 8
Views: 7203
Reputation: 13
If you are using this in 2021 this is an example of a logger.js using MONGODB
mongodb://<username>:<password>@mernshopping-shard-00-00.tzqom.mongodb.net:27017,mernshopping-shard-00-01.tzqom.mongodb.net:27017,mernshopping-shard-00-02.tzqom.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=MernShopping-shard-0&authSource=admin&retryWrites=true&w=majority
const {createLogger, format, transports} =require('winston');
require('winston-mongodb');
const env= require('dotenv');
env.config();
const MONGO_URI = process.env.WINSTON_MONGODB_URI;
module.exports = createLogger({
transports:[
// File transport
new transports.File({
filename: 'logs/winstonLogs.log',
format:format.combine(
format.timestamp({format: 'MMM-DD-YYYY HH:mm:ss'}),
format.align(),
format.printf(info => `${info.level}: ${[info.timestamp]}: ${info.message}`),
)}),
new transports.MongoDB({
level:'info',
db: MONGO_URI,
options:{
useUnifiedTopology:true
},
collection:'server_logs',
format:format.combine(
format.timestamp(),
//convert logs to a json format for mongodb
format.json()
)
})
]
})
Upvotes: 1
Reputation: 5807
It should be so simple, it will be all in one line:
db : 'mongodb://myuser:[email protected]:54545/MyLogDB
Upvotes: 3
Reputation: 2327
I was having a similar issue. It turned out the problem for me was that the Winston MongoDB transport expects the host option to be just the host name and I was prefixing it with mongodb://
.
The following works for me after removing mongodb://
from mongodb://123456.mongolab.com
:
var logger = new(winston.Logger)({
transports : [
new(winston.transports.MongoDB)({
db : 'logs',
host : '123456.mongolab.com',
username : 'username',
password : 'password'
})
]
});
Upvotes: 5