【问题标题】:Mongodb moongose log tableMongodb猫鼬日志表
【发布时间】:2021-05-02 17:01:00
【问题描述】:

我对如何在每次用户提出请求时创建将数据写入自己的表中的日志表感兴趣。 以及如何获取这样的数据:

{
            _id: ObjectId('4f442120eb03305789000000'),
            host: "127.0.0.1",
            logname: null,
            user: 'frank',
            time: ISODate("2000-10-10T20:55:36Z"),
            path: "/apache_pb.gif",
            request: "GET /apache_pb.gif HTTP/1.0",
            status: 200,
            response_size: 2326,
            referrer: "[http://www.example.com/start.html](http://www.example.com/start.html)",
            user_agent: "Mozilla/4.08 [en] (Win98; I ;Nav)"
            }

也许不是所有这些数据,但至少是提出请求的人、请求的类型、路径和时间。 我正在使用 nodejs、mongodb、mongoose。

【问题讨论】:

  • 所有请求信息都在请求头中。我会建议你创建一个具有所需字段的对象,然后插入到 mongo 数据库中。您不必使用任何 3rd 方包。

标签: javascript mongodb mongoose logging database-design


【解决方案1】:

您可以编写一个 middleware 来记录所有请求,发送到您的服务器和 MongoDB 数据库。

使用这些 npm 包,您可以轻松获取所需的信息,

1 - useragent

2 - express-useragent

【讨论】:

    【解决方案2】:

    我就是这样解决的。

    我的中间人

    const Log = require("../models/log");
    
    const log = async (req, res, next) => {
        try {
    
        let user_id = req.user.id
        let firstName = req.user.firstName
        let method = req.method
        let path = req.path    
    
        const log = new Log({ user_id, firstName, method, path });
    
        try {
            await log.save()
        } catch (e) {
            res.status(400).send(e)
        }
    
          next();
        } catch (e) {
          res.status(401).send(e);
        }
      };
    
    module.exports = log;
    

    型号

    const mongoose = require('mongoose')
    
    const logSchema = new mongoose.Schema({
        user_id: {
            type: String,
        },
        firstName: {
            type: String,
        },
        method: {
            type: String,
        },
        path: {
            type: String,
        },
    }, {
        timestamps: true
    })
    
    const Log = mongoose.model('Log', logSchema);
    
    module.exports = Log;
    

    和路由器

    const express = require('express')
    const Log = require('../models/log')
    const auth = require('../middleware/auth')
    const router = new express.Router()
    
    //Create log
    router.post('/logs', async (req, res) => {
        const log = new Log({
            ...req.body
        })
    
        try {
            await log.save()
            res.status(201).send(log)
        } catch (e) {
            res.status(400).send(e)
        }
    })
    
    //Sort and search
    router.get('/logs', auth, async (req, res) => {
        const match = {}
        const sort = {}
    
        if (req.query.completed) {
            match.completed = req.query.completed === 'true'
        }
    
        if (req.query.sortBy) {
            const parts = req.query.sortBy.split(':')
            sort[parts[0]] = parts[1] === 'desc' ? -1 : 1
        }
    
        try {
            await req.user.populate({
                path: 'logs',
                match,
                options: {
                    limit: parseInt(req.query.limit),
                    skip: parseInt(req.query.skip),
                    sort
                }
            }).execPopulate()
            res.send(req.user.logs)
        } catch (e) {
            res.status(500).send()
        }
    })
    
    module.exports = router;
    

    【讨论】:

      猜你喜欢
      • 2017-10-08
      • 1970-01-01
      • 2021-06-01
      • 2013-12-03
      • 2014-01-27
      • 2014-06-30
      • 2013-05-19
      • 1970-01-01
      • 2012-02-17
      相关资源
      最近更新 更多