7

我正在使用 winston 库:https ://github.com/flatiron/winston 尝试将数据存储到 mongodb 数据库:https ://github.com/indexzero/winston-mongodb

插入我使用的数据:

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());

但是,当我尝试使用以下方法查询数据时:

winston.query(options, function (err, results) {
    if (err) {console.log(err);}
    console.log(results);
});

我得到:

{}

它适用于控制台,并且我正在使用 Mongoose 库在应用程序的其他部分中使用数据库。

4

3 回答 3

5

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'
        })
    ]
});
于 2013-07-22T04:06:36.303 回答
3

它应该很简单,它将全部在一行中:

db : 'mongodb://myuser:mypass@ds047777.mongolab.com:54545/MyLogDB
于 2015-12-08T10:26:18.793 回答
0

如果您在 2021 年使用它,这是使用 MONGODB 的 logger.js 示例

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()
                )
    })
    ]
})
于 2021-09-25T17:16:11.583 回答