如何将 winston log 库记录的日志写入 mongo DB 数据库
官網
Winston 非常適合配置不同的日志目的地。 在我們的小應用程序中,讓我們創建另一個傳輸。 這次我想把日志保存到一個數據庫中,MongoDB 簡潔一些。 在 logger.js 文件上,復制以下代碼塊。 確保安裝 Winston MongoDB,即 npm install winston-mongodb。
How to use MongoDB
下載并安裝 MongoDB 社區服務器。
導航到您的環境變量(對于 Windows 用戶),在用戶變量下,選擇路徑 → 編輯 → 新建,添加 C:\Program Files\MongoDB\Server\4.4\bin(4.4 可能因您計算機上安裝的 MongoDB 版本而異).
打開命令提示符并鍵入 mongo。 這將檢查您是否已成功安裝 MongoDB。 MongoDB shell 版本將打印在您的終端上,這意味著您的安裝成功。
輸入 use logs 創建數據庫日志。
輸入 db.createCollection(“server_logs”) 以創建 collection.
在 logger.js 里插入下列代碼:
const { createLogger, format, transports } = require('winston');// Import mongodb require('winston-mongodb');module.exports = createLogger({ transports:[// File transportnew transports.File({filename: 'logs/server.log',format:format.combine(format.timestamp({format: 'MMM-DD-YYYY HH:mm:ss'}),format.align(),format.printf(info => `${info.level}: ${[info.timestamp]}: ${info.message}`), )}),// MongoDB transportnew transports.MongoDB({level: 'error',//mongo database connection linkdb : 'mongodb://localhost:27017/logs',options: {useUnifiedTopology: true},// A collection to save json formatted logscollection: 'server_logs',format: format.combine(format.timestamp(),// Convert logs to a json formatformat.json())})] });運行 node app.js 以啟動服務器并訪問以下 URL 以觸發服務器響應和請求。
http://localhost:3000/
http://localhost:3000/calc
http://localhost:3000/hello
日志將記錄到 server.log 文件中。 打開 server.log 查看記錄的日志。
任何錯誤日志都將記錄在 MongoDB 數據庫中。
輸入 db.server_logs.find() 以查看日志。
MongoDB 傳輸采用 JSON 格式。 要將這些日志保存在 Mongo 數據庫中,我們需要將它們轉換為 JSON 格式。 這是將記錄插入 Mongo 數據庫集合的唯一格式。
更多Jerry的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的如何将 winston log 库记录的日志写入 mongo DB 数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PPT文档页数显示的增加和更新
- 下一篇: 命运冠位指定银棋在哪里刷 命运冠位指定银