Skip to content

Commit 6127ba8

Browse files
committed
merge
2 parents 0272620 + 9d81162 commit 6127ba8

7 files changed

+84
-2106
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
node_modules
22
npm-debug.log
33
.idea
4+
.env

README.md

+55-45
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
# winston
1+
# winston-mongodb
22

33
A MongoDB transport for [winston][0].
44

5-
Current version supports only mongodb driver version 3.x and winston 3.x. If you want to use
6-
winston-mongodb with mongodb version 1.4.x use winston-mongodb <1.x. For mongodb 2.x use
7-
winston-mongodb <3.x.
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.
88

99
## Motivation
1010
`tldr;?`: To break the [winston][0] codebase into small modules that work
@@ -17,51 +17,61 @@ and a File is overkill.
1717

1818
## Usage
1919
``` js
20-
var winston = require('winston');
20+
const winston = require('winston');
21+
// Requiring `winston-mongodb` will expose winston.transports.MongoDB`
22+
require('winston-mongodb');
2123

22-
/**
23-
* Requiring `winston-mongodb` will expose
24-
* `winston.transports.MongoDB`
25-
*/
26-
require('winston-mongodb');
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});
2751

28-
winston.add(new winston.transports.MongoDB(options));
2952
```
3053

31-
The MongoDB transport takes the following options. 'db' is required:
32-
33-
* __level:__ Level of messages that this transport should log, defaults to
34-
'info'.
35-
* __silent:__ Boolean flag indicating whether to suppress output, defaults to
36-
false.
37-
* __db:__ MongoDB connection uri, pre-connected `MongoClient` object or promise
38-
which resolves to a pre-connected `MongoClient` object.
39-
* __dbName:__ The database name to connect to, defaults to DB name based on
40-
connection URI if not provided, ignored if using a pre-connected mongoose connection.
41-
* __options:__ MongoDB connection parameters (optional, defaults to
42-
`{poolSize: 2, autoReconnect: true, useNewUrlParser: true}`).
43-
* __collection__: The name of the collection you want to store log messages in,
44-
defaults to 'log'.
45-
* __storeHost:__ Boolean indicating if you want to store machine hostname in
46-
logs entry, if set to true it populates MongoDB entry with 'hostname' field,
47-
which stores os.hostname() value.
48-
* __label:__ Label stored with entry object if defined.
49-
* __name:__ Transport instance identifier. Useful if you need to create multiple
50-
MongoDB transports.
51-
* __capped:__ In case this property is true, winston-mongodb will try to create
52-
new log collection as capped, defaults to false.
53-
* __cappedSize:__ Size of logs capped collection in bytes, defaults to 10000000.
54-
* __cappedMax:__ Size of logs capped collection in number of documents.
55-
* __tryReconnect:__ Will try to reconnect to the database in case of fail during
56-
initialization. Works only if __db__ is a string. Defaults to false.
57-
* __decolorize:__ Will remove color attributes from the log entry message,
58-
defaults to false.
59-
* __leaveConnectionOpen:__ Will leave MongoClient connected after transport shut down.
60-
* __metaKey:__ Configure which key is used to store metadata in the logged info object.
61-
Defaults to `'metadata'` to remain compatible with the [metadata format](https://github.com/winstonjs/logform/blob/master/examples/metadata.js)
62-
* __expireAfterSeconds:__ Seconds before the entry is removed. Works only if __capped__ is not set.
63-
64-
*Metadata:* Logged as a native JSON object in 'meta' property.
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.<br/>Defaults to `{poolSize: 2, autoReconnect: true, useNewUrlParser: true}`). |
61+
| collection | The name of the collection you want to store log messages in.<br/>Defaults to `log`. |
62+
| level | Level of messages that this transport should log.<br/>Defaults to `info`. |
63+
| silent | Boolean flag indicating whether to suppress output.<br/>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.<br/>Defaults to `false`. |
68+
| cappedSize | Size of logs capped collection in bytes.<br/>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.<br/>Defaults to `false`. |
71+
| decolorize | Will remove color attributes from the log entry message.<br/>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.<br/>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. |
6575

6676
*Logging unhandled exceptions:* For logging unhandled exceptions specify
6777
winston-mongodb as `handleExceptions` logger according to winston documentation.

lib/winston-mongodb.d.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ declare module 'winston-mongodb' {
4646
/**
4747
* MongoDB connection uri, pre-connected db object or promise object which will be resolved with pre-connected db object.
4848
*
49-
* @type {(string | Promise<any>)}
49+
* @type {(string | Promise<object>)}
5050
* @memberof MongoDBConnectionOptions
5151
*/
5252
db: string | Promise<any>;

lib/winston-mongodb.js

+11-3
Original file line numberDiff line numberDiff line change
@@ -217,12 +217,20 @@ MongoDB.prototype.log = function(info, cb) {
217217
}
218218
const decolorizeRegex = new RegExp(/\u001b\[[0-9]{1,2}m/g);
219219
let entry = { timestamp: new Date(), level: (this.decolorize) ? info.level.replace(decolorizeRegex, '') : info.level };
220-
let message = util.format(info.message, ...(info.splat || []));
221-
entry.message = (this.decolorize) ? message.replace(decolorizeRegex, '') : message;
222-
entry.meta = helpers.prepareMetaData(info[this.metaKey]);
220+
let msg = util.format(info.message, ...(info.splat || []));
221+
entry.message = (this.decolorize) ? msg.replace(decolorizeRegex, '') : msg;
222+
// get 'meta' object from info object - as per winston doc: Properties besides level and message are considered as "meta".
223+
const {level, message, ...meta} = info;
224+
// prepare meta object for storage
225+
const metaData = helpers.prepareMetaData(meta);
226+
// if metadata is not empty object add it to entry - makes no sense to store empty object
227+
if (Object.keys(metaData).length > 0) {
228+
entry[this.metaKey] = metaData;
229+
}
223230
if (this.storeHost) {
224231
entry.hostname = this.hostname;
225232
}
233+
226234
if (this.label) {
227235
entry.label = this.label;
228236
}

0 commit comments

Comments
 (0)