├── .eslintrc
├── .github
├── ISSUE_TEMPLATE
│ ├── bug_report.yml
│ ├── config.yml
│ └── feature_request.yml
├── dependabot.yml
└── workflows
│ └── ci.yml
├── .gitignore
├── .npmignore
├── README.md
├── lib
├── helpers.js
├── winston-mongodb.d.ts
└── winston-mongodb.js
├── package-lock.json
├── package.json
└── test
├── helpers-test.js
└── winston-mongodb-test.js
/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "@dabh/eslint-config-populist",
3 | "rules": {
4 | "one-var": ["error", { "var": "never", "let": "never", "const": "never" }],
5 | "no-unused-vars": ["error", { "ignoreRestSiblings": true }],
6 | "no-undefined": "off",
7 | "no-console": "off",
8 | "strict": "off"
9 | },
10 | "parserOptions": {
11 | "ecmaVersion": 2022
12 | },
13 | "env": {
14 | "es2020": true
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.yml:
--------------------------------------------------------------------------------
1 | name: Have you encountered an issue?
2 | description: Report an issue with Winston.
3 | title: "[Bug]: "
4 | labels: ["Bug", "Needs Investigation"]
5 | body:
6 | - type: markdown # Form Header
7 | attributes:
8 | value: >-
9 | This issue form is for reporting bugs only!
10 | - type: input # Search Terms
11 | validations:
12 | required: true
13 | attributes:
14 | label: 🔎 Search Terms
15 | description: >-
16 | What search terms did you use when trying to find an existing bug report, looking in both open and closed issues?
17 | List them here (comma seperated) so people in the future can find this one more easily.
18 | - type: textarea # Problem Definition
19 | validations:
20 | required: true
21 | attributes:
22 | label: The problem
23 | description: >-
24 | Please provide a clear and concise description of the problem you've encountered and what the
25 | expected behavior was.
26 | - type: markdown # Environment Section Header
27 | attributes:
28 | value: |
29 | ## Environment
30 | - type: input # Affected Version Input
31 | id: winston-version
32 | validations:
33 | required: true
34 | attributes:
35 | label: What version of Winston presents the issue?
36 | placeholder: v3.4.0
37 | description: >
38 | Can be found by running one of the following (depending on your package manager of choice):
39 | - `npm list winston`
40 | - `yarn list --pattern winston`
41 | - type: input # Affected Version Input
42 | id: node-version
43 | validations:
44 | required: true
45 | attributes:
46 | label: What version of Node are you using?
47 | placeholder: v16.8.0
48 | description: >
49 | Can be found by running the following: `node -v`
50 | - type: input # Last Known Working Version
51 | attributes:
52 | label: If this worked in a previous version of Winston, which was it?
53 | placeholder: v3.0.0
54 | description: >
55 | If known, otherwise please leave blank.
56 | - type: markdown # Details Section Header
57 | attributes:
58 | value: |
59 | # Details
60 | - type: textarea # Minimum Working Example Input
61 | attributes:
62 | label: Minimum Working Example
63 | description: |
64 | If you can, providing an MWE to reproduce the issue you're encountering can greatly speed up
65 | investigation into the issue by one of our maintainers, or anyone else in the community who's looking
66 | to get involved.
67 |
68 | This can be as simple as a script, a link to a repo, etc.
69 | If using a script please wrap with triple backticks and language. EG:
70 | ` ```javascript `
71 | - type: textarea # Additional Information
72 | attributes:
73 | label: Additional information
74 | description: >
75 | If you have any additional information for us that you feel will be valuable, please use the field below.
76 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
1 | blank_issues_enabled: false
2 | contact_links:
3 | - name: Have a formatting issue or feature request?
4 | url: https://github.com/winstonjs/logform/issues/new/choose
5 | about: Please search and report @ WinstonJS/Logform
6 | - name: Need help using Winston?
7 | url: https://stackoverflow.com/questions/tagged/winston
8 | about: Please look on StackOverflow first to see if someone has already answered your question.
9 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.yml:
--------------------------------------------------------------------------------
1 | name: Would you like to see a feature implemented?
2 | description: Request a new feature for Winston
3 | title: "[Feature Request]: "
4 | labels: ["Feature Request", "Needs Investigation"]
5 | body:
6 | - type: markdown # Form Header
7 | attributes:
8 | value: |
9 | This issue form is for requesting features only!
10 | - type: input # Search Terms
11 | validations:
12 | required: true
13 | attributes:
14 | label: 🔎 Search Terms
15 | description: >-
16 | What search terms did you use when trying to find an existing feature request, looking in both open and closed issues?
17 | List them here (comma seperated) so people in the future can find this one more easily.
18 | - type: textarea # Feature Definition
19 | validations:
20 | required: true
21 | attributes:
22 | label: The vision
23 | description: >-
24 | Please provide a clear and concise description of the feature you would like to see implemented.
25 | - type: markdown # Feature Details Section
26 | attributes:
27 | value: |
28 | # Details
29 | - type: textarea # Use Case Input
30 | attributes:
31 | label: Use case
32 | description: |
33 | If you desire you can provide use cases for the requested feature.
34 | - type: textarea # Additional Information
35 | attributes:
36 | label: Additional information
37 | description: >
38 | If you have any additional information for us that you feel will be valuable, please use the field below.
39 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: github-actions
4 | directory: /
5 | schedule:
6 | interval: weekly
7 | - package-ecosystem: npm
8 | directory: /
9 | schedule:
10 | interval: weekly
11 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | pull_request:
5 | branches:
6 | - main
7 | - master
8 | push:
9 | branches:
10 | - main
11 | - master
12 |
13 | jobs:
14 | unit-tests:
15 | runs-on: ubuntu-latest
16 | strategy:
17 | matrix:
18 | node:
19 | - 16
20 | - 18
21 | - 20
22 | mongo:
23 | - v6.0-latest
24 | - v5.0-latest
25 | - v4.4-latest
26 | steps:
27 | - uses: actions/checkout@v4
28 | - uses: actions/setup-node@v4
29 | with:
30 | node-version: ${{ matrix.node }}
31 | - name: Install Dependencies
32 | env:
33 | MONGOMS_VERSION: ${{ matrix.mongo }}
34 | MONGOMS_DISABLE_POSTINSTALL: 0
35 | run: npm clean-install
36 | - name: Lint
37 | run: npm run lint
38 | - name: Test
39 | env:
40 | MONGOMS_VERSION: ${{ matrix.mongo }}
41 | run: npm test
42 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | npm-debug.log
3 | .idea
4 | .env
5 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | .git*
2 | npm-debug.log
3 | .idea
4 | .eslintrc
5 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # winston-mongodb
2 |
3 | A MongoDB transport for [winston][0].
4 |
5 | Current version supports only mongodb driver version 3.x and newer and winston 3.x and newer.
6 | If you want to use winston-mongodb with mongodb version 1.4.x use winston-mongodb <1.x.
7 | For mongodb 2.x use winston-mongodb <3.x.
8 |
9 | ## Motivation
10 | `tldr;?`: To break the [winston][0] codebase into small modules that work
11 | together.
12 |
13 | The [winston][0] codebase has been growing significantly with contributions and
14 | other logging transports. This is **awesome**. However, taking a ton of
15 | additional dependencies just to do something simple like logging to the Console
16 | and a File is overkill.
17 |
18 | ## Usage
19 | ``` js
20 | const winston = require('winston');
21 | // Requiring `winston-mongodb` will expose winston.transports.MongoDB`
22 | require('winston-mongodb');
23 |
24 | const log = winston.createLogger({
25 | level: 'info',
26 | transports: [
27 | // write errors to console too
28 | new winston.transports.Console({format: winston.format.simple(), level:'error'})
29 | ],
30 | });
31 |
32 | // logging to console so far
33 | log.info('Connecting to database...');
34 |
35 | const MongoClient = require('mongodb').MongoClient;
36 | const url = "mongodb://localhost:27017/mydb";
37 |
38 | const client = new MongoClient(url);
39 | await client.connect();
40 |
41 | const transportOptions = {
42 | db: await Promise.resolve(client),
43 | collection: 'log'
44 | };
45 |
46 | log.add(new winston.transports.MongoDB(transportOptions));
47 |
48 | // following entry should appear in log collection and will contain
49 | // metadata JSON-property containing url field
50 | log.info('Connected to database.',{url});
51 |
52 | ```
53 |
54 | The MongoDB transport takes the following options. Only option `db` is required:
55 |
56 | | Option | Description |
57 | | ------ | :----------------------------------------------- |
58 | | db | **REQUIRED**. MongoDB connection uri, pre-connected `MongoClient` object or promise which resolves to a pre-connected `MongoClient` object. |
59 | | dbname | The database name to connect to, defaults to DB name based on connection URI if not provided, ignored if using a pre-connected connection. |
60 | | options| MongoDB connection parameters.
Defaults to `{maxPoolSize: 2}`). |
61 | | collection | The name of the collection you want to store log messages in.
Defaults to `log`. |
62 | | level | Level of messages that this transport should log.
Defaults to `info`. |
63 | | silent | Boolean flag indicating whether to suppress output.
Defaults to `false`. |
64 | | storeHost | Boolean indicating if you want to store machine hostname in logs entry, if set to true it populates MongoDB entry with 'hostname' field, which stores os.hostname() value. |
65 | | label | If set to true, then label attribute content will be stored in `label` field, if detected in meta-data. |
66 | | name | Transport instance identifier. Useful if you need to create multiple MongoDB transports. |
67 | | capped | In case this property is true, winston-mongodb will try to create new log collection as capped.
Defaults to `false`. |
68 | | cappedSize | Size of logs capped collection in bytes.
Defaults to 10,000,000. |
69 | | cappedMax | Size of logs capped collection in number of documents. |
70 | | tryReconnect | Will try to reconnect to the database in case of fail during initialization. Works only if __db__ is a string.
Defaults to `false`. |
71 | | decolorize | Will remove color attributes from the log entry message.
Defaults to `false`. |
72 | | leaveConnectionOpen| Will leave MongoClient connected after transport shuts down. |
73 | | metaKey | Configure name of the field which is used to store metadata in the logged info object.
Defaults to `metadata` to remain compatible with the [metadata format](https://github.com/winstonjs/logform/blob/master/examples/metadata.js) |
74 | | expireAfterSeconds |Seconds before the entry is removed. Works only if __capped__ is not set. |
75 |
76 | *Logging unhandled exceptions:* For logging unhandled exceptions specify
77 | winston-mongodb as `handleExceptions` logger according to winston documentation.
78 |
79 | ## Querying and streaming logs
80 |
81 | Besides supporting the main options from winston, this transport supports the
82 | following extra options:
83 |
84 | * __includeIds:__ Whether the returned logs should include the `_id` attribute
85 | settled by mongodb, defaults to `false`.
86 |
87 | ## Installation
88 |
89 | ``` bash
90 | $ npm install winston
91 | $ npm install winston-mongodb
92 | ```
93 |
94 | ## [Changelog](https://github.com/winstonjs/winston-mongodb/releases)
95 |
96 | #### Author: [Charlie Robbins](http://blog.nodejitsu.com)
97 | #### Contributors: [Yurij Mikhalevich](https://github.com/yurijmikhalevich), [Kendrick Taylor](https://github.com/sktaylor), [Yosef Dinerstein](https://github.com/yosefd), [Steve Dalby](https://github.com/stevedalby)
98 |
99 | [0]: https://github.com/winstonjs/winston
100 |
--------------------------------------------------------------------------------
/lib/helpers.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @module helpers
3 | * @fileoverview Helpers for winston-mongodb
4 | * @license MIT
5 | * @author 0@39.yt (Yurij Mikhalevich)
6 | */
7 | 'use strict';
8 | const ObjectId = require('mongodb').ObjectId;
9 |
10 |
11 | /**
12 | * Prepares metadata to store into database.
13 | * @param {Object} meta Metadata
14 | * @returns {Object} Prepared metadata
15 | */
16 | exports.prepareMetaData = meta => {
17 | return cloneMeta(meta);
18 | };
19 |
20 |
21 | /**
22 | * Clones meta object and cleans it from circular references, replacing them
23 | * with string '[Circular]' and fixes field names to be storable within
24 | * MongoDB
25 | * @param {Object} node Current object or its leaf
26 | * @param {Array} optParents Object's parents
27 | * @returns {Object} Adjusted clone of object
28 | */
29 | function cloneMeta(node, optParents) {
30 | if (!((node !== null && typeof node === 'object') || typeof node === 'function')
31 | || (node instanceof ObjectId) || (node instanceof Buffer)) {
32 | return node;
33 | }
34 | let copy = Array.isArray(node) ? [] : {};
35 | if (node instanceof Date) {
36 | return new Date(node.getTime());
37 | } else if (node instanceof Error) {
38 | // This is needed because Error's message, name and stack isn't accessible when cycling through properties
39 | copy = { message: node.message, name: node.name, stack: node.stack };
40 | }
41 | optParents = optParents || [];
42 | optParents.push(node);
43 | for (const key in node) {
44 | if (!Object.prototype.hasOwnProperty.call(node, key)) {
45 | continue;
46 | }
47 | const value = node[key];
48 | let newKey = key;
49 | if (newKey.includes('.') || newKey.includes('$')) {
50 | newKey = newKey.replace(/\./g, '[dot]').replace(/\$/g, '[$]');
51 | }
52 | if ((value !== null && typeof value === 'object') || typeof value === 'function') {
53 | if (optParents.indexOf(value) === -1) {
54 | copy[newKey] = cloneMeta(value, optParents);
55 | } else {
56 | copy[newKey] = '[Circular]';
57 | }
58 | } else {
59 | copy[newKey] = value;
60 | }
61 | }
62 | optParents.pop();
63 | return copy;
64 | }
65 |
--------------------------------------------------------------------------------
/lib/winston-mongodb.d.ts:
--------------------------------------------------------------------------------
1 | // Type definitions for winston-mongodb
2 | // Project: https://github.com/winstonjs/winston-mongodb
3 | // Definitions by: miton18 , blove ,
4 | // Balazs Mocsai
5 |
6 | import { Logform, transports } from "winston";
7 | import { MongoDBTransportInstance, MongoDBConnectionOptions } from 'winston-mongodb';
8 |
9 | /**
10 | * Extending transport
11 | */
12 | declare module 'winston/lib/winston/transports' {
13 | export interface Transports {
14 | MongoDB: MongoDBTransportInstance;
15 | MongoDBTransportOptions: MongoDBConnectionOptions;
16 | }
17 | }
18 |
19 | declare module 'winston-mongodb' {
20 | export interface MongoDBTransportInstance extends transports.StreamTransportInstance {
21 | new (options?: MongoDBConnectionOptions) : MongoDBTransportInstance;
22 | query: (callback: Function, options?: any) => Promise;
23 | }
24 |
25 | /**
26 | * Options for transport
27 | *
28 | * @export
29 | * @interface MongoDBConnectionOptions
30 | */
31 | export interface MongoDBConnectionOptions {
32 | /**
33 | * Level of messages that this transport should log, defaults to 'info'.
34 | *
35 | * @type {string}
36 | * @memberof MongoDBConnectionOptions
37 | */
38 | level?: string;
39 | /**
40 | * Boolean flag indicating whether to suppress output, defaults to false.
41 | *
42 | * @type {boolean}
43 | * @memberof MongoDBConnectionOptions
44 | */
45 | silent?: boolean;
46 | /**
47 | * MongoDB connection uri, pre-connected db object or promise object which will be resolved with pre-connected db object.
48 | *
49 | * @type {(string | Promise