Skip to content

Commit f2885c0

Browse files
authored
feat: rewrite Logging via debug package under DEBUG=MongoMS:* key (#270)
* Add Dev-dependency "@types/debug" * Change Typescript lib from "es2017" to "esnext" * Added some Logging to "MongoBinaryDownloadUrl" Transformed logging to use "debug" "resolve-config" now gets loaded in index as an side-effect (load MONGOMS_DEBUG) Added "Enable Debug Mode" section to README Reorganized the README's documented options * Remove "console.warn" check, because it dosnt run when debug is enabled
1 parent bd40272 commit f2885c0

17 files changed

+168
-173
lines changed

README.md

Lines changed: 68 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ _Note: the package does try to download `mongod` upon server start if it cannot
8080

8181
## Usage
8282

83-
### Simple server start:
83+
### Simple server start
8484

8585
```js
8686
import { MongoMemoryServer } from 'mongodb-memory-server';
@@ -108,7 +108,7 @@ mongod.getInstanceInfo();
108108
// special childProcess killer will shutdown it for you
109109
```
110110

111-
### Available options
111+
### Available options for MongoMemoryServer
112112

113113
All options are optional.
114114

@@ -120,7 +120,6 @@ const mongod = new MongoMemoryServer({
120120
dbName?: string, // by default generate random dbName
121121
dbPath?: string, // by default create in temp directory
122122
storageEngine?: string, // by default `ephemeralForTest`, available engines: [ 'devnull', 'ephemeralForTest', 'mmapv1', 'wiredTiger' ]
123-
debug?: boolean, // by default false
124123
replSet?: string, // by default no replica set, replica set name
125124
auth?: boolean, // by default `mongod` is started with '--noauth', start `mongod` with '--auth'
126125
args?: string[], // by default no additional arguments, any additional command line arguments for `mongod` `mongod` (ex. ['--notablescan'])
@@ -130,66 +129,19 @@ const mongod = new MongoMemoryServer({
130129
downloadDir?: string, // by default node_modules/.cache/mongodb-memory-server/mongodb-binaries
131130
platform?: string, // by default os.platform()
132131
arch?: string, // by default os.arch()
133-
debug?: boolean, // by default false
134132
checkMD5?: boolean, // by default false OR process.env.MONGOMS_MD5_CHECK
135133
systemBinary?: string, // by default undefined or process.env.MONGOMS_SYSTEM_BINARY
136134
},
137-
debug?: boolean, // by default false
138135
autoStart?: boolean, // by default true
139136
});
140137
```
141138

142-
#### Options which can be set via ENVIRONMENT variables
143-
144-
```sh
145-
MONGOMS_DOWNLOAD_DIR=/path/to/mongodb/binaries
146-
MONGOMS_PLATFORM=linux
147-
MONGOMS_ARCH=x64
148-
MONGOMS_VERSION=3
149-
MONGOMS_DEBUG=1 # also available case-insensitive values: "on" "yes" "true"
150-
MONGOMS_DOWNLOAD_MIRROR=host # your mirror host to download the mongodb binary
151-
MONGOMS_DOWNLOAD_URL=url # full URL to download the mongodb binary
152-
MONGOMS_DISABLE_POSTINSTALL=1 # if you want to skip download binaries on `npm i` command
153-
MONGOMS_SYSTEM_BINARY=/usr/local/bin/mongod # if you want to use an existing binary already on your system.
154-
MONGOMS_MD5_CHECK=1 # if you want to make MD5 check of downloaded binary.
155-
# Passed constructor parameter `binary.checkMD5` has higher priority.
156-
157-
# GetOS specific ones (for linux only)
158-
MONGOMS_USE_LINUX_LSB_RELEASE # Only try "lsb_release -a"
159-
MONGOMS_USE_LINUX_OS_RELEASE # Only try to read "/etc/os-release"
160-
MONGOMS_USE_LINUX_ANYFILE_RELEASE # Only try to read the first file found "/etc/*-release"
161-
```
162-
163-
#### Options which can be set via package.json's `config` section
164-
165-
You can also use package.json's `config` section to configure installation process.
166-
Environment variables have higher priority than contents of package.json.
167-
168-
```json
169-
{
170-
"config": {
171-
"mongodbMemoryServer": {
172-
"downloadDir": "/path/to/mongodb/binaries",
173-
"platform": "linux",
174-
"arch": "x64",
175-
"version": "3",
176-
"debug": "1",
177-
"downloadMirror": "url",
178-
"disablePostinstall": "1",
179-
"systemBinary": "/usr/local/bin/mongod",
180-
"md5Check": "1"
181-
}
182-
}
183-
}
184-
```
185-
186-
### Replica Set start:
139+
### Replica Set start
187140

188141
```js
189142
import { MongoMemoryReplSet } from 'mongodb-memory-server';
190143

191144
const replSet = new MongoMemoryReplSet({
192-
debug: false,
193145
replSet: { storageEngine: 'wiredTiger' },
194146
});
195147
await replSet.waitUntilRunning();
@@ -214,15 +166,14 @@ replSet.stop();
214166
// or it should be stopped automatically when you exit from script
215167
```
216168

217-
### Available options for Replica Set
169+
### Available options for MongoMemoryReplSet
218170

219171
All options are optional.
220172

221173
```js
222174
const replSet = new MongoMemoryReplSet({
223175
autoStart, // same as for MongoMemoryServer
224176
binary: binaryOpts, // same as for MongoMemoryServer
225-
debug, // same as for MongoMemoryServer
226177
instanceOpts: [
227178
{
228179
args, // any additional instance specific args
@@ -255,6 +206,50 @@ const replSet = new MongoMemoryReplSet({
255206
});
256207
```
257208

209+
### Options which can be set via ENVIRONMENT variables
210+
211+
```sh
212+
MONGOMS_DOWNLOAD_DIR=/path/to/mongodb/binaries
213+
MONGOMS_PLATFORM=linux
214+
MONGOMS_ARCH=x64
215+
MONGOMS_VERSION=3
216+
MONGOMS_DEBUG=1 # also available case-insensitive values: "on" "yes" "true"
217+
MONGOMS_DOWNLOAD_MIRROR=host # your mirror host to download the mongodb binary
218+
MONGOMS_DOWNLOAD_URL=url # full URL to download the mongodb binary
219+
MONGOMS_DISABLE_POSTINSTALL=1 # if you want to skip download binaries on `npm i` command
220+
MONGOMS_SYSTEM_BINARY=/usr/local/bin/mongod # if you want to use an existing binary already on your system.
221+
MONGOMS_MD5_CHECK=1 # if you want to make MD5 check of downloaded binary.
222+
# Passed constructor parameter `binary.checkMD5` has higher priority.
223+
224+
# GetOS specific ones (for linux only)
225+
MONGOMS_USE_LINUX_LSB_RELEASE # Only try "lsb_release -a"
226+
MONGOMS_USE_LINUX_OS_RELEASE # Only try to read "/etc/os-release"
227+
MONGOMS_USE_LINUX_ANYFILE_RELEASE # Only try to read the first file found "/etc/*-release"
228+
```
229+
230+
### Options which can be set via package.json's `config` section
231+
232+
You can also use package.json's `config` section to configure installation process.
233+
Environment variables have higher priority than contents of package.json.
234+
235+
```json
236+
{
237+
"config": {
238+
"mongodbMemoryServer": {
239+
"downloadDir": "/path/to/mongodb/binaries",
240+
"platform": "linux",
241+
"arch": "x64",
242+
"version": "3",
243+
"debug": "1",
244+
"downloadMirror": "url",
245+
"disablePostinstall": "1",
246+
"systemBinary": "/usr/local/bin/mongod",
247+
"md5Check": "1"
248+
}
249+
}
250+
}
251+
```
252+
258253
### Simple test with MongoClient
259254

260255
Take a look at this [test file](https://github.com/nodkz/mongodb-memory-server/blob/master/packages/mongodb-memory-server-core/src/__tests__/singleDB-test.ts).
@@ -468,6 +463,26 @@ There isn't currently an official MongoDB release for alpine linux. This means t
468463
built in and then set the MONGOMS_SYSTEM_BINARY variable to point at that binary. This should allow you to use
469464
mongodb-memory-server on any system on which you can install mongod.
470465

466+
### Enable Debug Mode
467+
468+
The Debug mode can be enabled with an Environment-Variable or in the package.json "config" section:
469+
470+
```sh
471+
MONGOMS_DEBUG=1 # also available case-insensitive values: "on" "yes" "true"
472+
```
473+
474+
or
475+
476+
```json
477+
{
478+
"config": {
479+
"mongodbMemoryServer": {
480+
"debug": "1", // also available case-insensitive values: "on" "yes" "true"
481+
}
482+
}
483+
}
484+
```
485+
471486
## Travis
472487

473488
**It is very important** to limit spawned number of Jest workers for avoiding race condition. Cause Jest spawn huge amount of workers for every node environment on same machine. [More details](https://github.com/facebook/jest/issues/3765)

packages/mongodb-memory-server-core/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
},
3636
"dependencies": {
3737
"@types/cross-spawn": "^6.0.1",
38+
"@types/debug": "^4.1.5",
3839
"@types/decompress": "^4.2.3",
3940
"@types/dedent": "^0.7.0",
4041
"@types/find-cache-dir": "^2.0.0",

packages/mongodb-memory-server-core/src/MongoMemoryReplSet.ts

Lines changed: 16 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,14 @@ import { MongoMemoryServerOptsT } from './MongoMemoryServer';
55
import { generateDbName, getHost } from './util/db_util';
66
import { MongoBinaryOpts } from './util/MongoBinary';
77
import {
8-
DebugFn,
98
MongoMemoryInstancePropT,
109
MongoMemoryInstancePropBaseT,
1110
SpawnOptions,
1211
StorageEngineT,
1312
} from './types';
13+
import debug from 'debug';
14+
15+
const log = debug('MongoMS:MongoMemoryReplSet');
1416

1517
/**
1618
* Replica set specific options.
@@ -50,7 +52,6 @@ export interface MongoMemoryReplSetOptsT {
5052
binary?: MongoBinaryOpts;
5153
replSet?: ReplSetOpts;
5254
autoStart?: boolean;
53-
debug?: boolean;
5455
}
5556

5657
export default class MongoMemoryReplSet extends EventEmitter {
@@ -59,11 +60,9 @@ export default class MongoMemoryReplSet extends EventEmitter {
5960
instanceOpts: MongoMemoryInstancePropBaseT[];
6061
binary: MongoBinaryOpts;
6162
replSet: Required<ReplSetOpts>;
62-
debug: boolean;
6363
autoStart?: boolean;
6464
};
6565

66-
debug: DebugFn;
6766
_state: 'init' | 'running' | 'stopped';
6867
admin?: mongodb.Admin;
6968

@@ -84,19 +83,14 @@ export default class MongoMemoryReplSet extends EventEmitter {
8483
this._state = 'stopped';
8584
this.opts = {
8685
binary: opts.binary || {},
87-
debug: !!opts.debug,
8886
instanceOpts: opts.instanceOpts || [],
8987
replSet: { ...replSetDefaults, ...opts.replSet },
9088
};
9189

9290
if (!this.opts.replSet.args) this.opts.replSet.args = [];
9391
this.opts.replSet.args.push('--oplogSize', `${this.opts.replSet.oplogSize}`);
94-
this.debug = (...args: any[]) => {
95-
if (!this.opts.debug) return;
96-
console.log(...args);
97-
};
9892
if (!(opts && opts.autoStart === false)) {
99-
this.debug('Autostarting MongoMemoryReplSet.');
93+
log('Autostarting MongoMemoryReplSet.');
10094
setTimeout(() => this.start(), 0);
10195
}
10296
process.on('beforeExit', () => this.stop());
@@ -134,7 +128,7 @@ export default class MongoMemoryReplSet extends EventEmitter {
134128
if (baseOpts.port) opts.port = baseOpts.port;
135129
if (baseOpts.dbPath) opts.dbPath = baseOpts.dbPath;
136130
if (baseOpts.storageEngine) opts.storageEngine = baseOpts.storageEngine;
137-
this.debug(' instance opts:', opts);
131+
log(' instance opts:', opts);
138132
return opts;
139133
}
140134

@@ -146,7 +140,7 @@ export default class MongoMemoryReplSet extends EventEmitter {
146140
await this._waitForPrimary();
147141
}
148142
if (this._state !== 'running') {
149-
throw new Error('Replica Set is not running. Use opts.debug for more info.');
143+
throw new Error('Replica Set is not running. Use debug for more info.');
150144
}
151145
let dbName: string;
152146
if (otherDb) {
@@ -163,22 +157,22 @@ export default class MongoMemoryReplSet extends EventEmitter {
163157
* Start underlying `mongod` instances.
164158
*/
165159
async start(): Promise<void> {
166-
this.debug('start');
160+
log('start');
167161
if (this._state !== 'stopped') {
168-
throw new Error(`Already in 'init' or 'running' state. Use opts.debug = true for more info.`);
162+
throw new Error(`Already in 'init' or 'running' state. Use debug for more info.`);
169163
}
170164
this.emit((this._state = 'init'));
171-
this.debug('init');
165+
log('init');
172166
// Any servers defined within `opts.instanceOpts` should be started first as
173167
// the user could have specified a `dbPath` in which case we would want to perform
174168
// the `replSetInitiate` command against that server.
175169
const servers = this.opts.instanceOpts.map((opts) => {
176-
this.debug(' starting server from instanceOpts:', opts, '...');
170+
log(' starting server from instanceOpts:', opts, '...');
177171
return this._initServer(this.getInstanceOpts(opts));
178172
});
179173
const cnt = this.opts.replSet.count || 1;
180174
while (servers.length < cnt) {
181-
this.debug(` starting ${cnt} servers...`);
175+
log(` starting ${cnt} servers...`);
182176
const server = this._initServer(this.getInstanceOpts({}));
183177
servers.push(server);
184178
}
@@ -201,7 +195,7 @@ export default class MongoMemoryReplSet extends EventEmitter {
201195
return true;
202196
})
203197
.catch((err) => {
204-
this.debug(err);
198+
log(err);
205199
this.emit((this._state = 'stopped'), err);
206200
return false;
207201
});
@@ -220,7 +214,7 @@ export default class MongoMemoryReplSet extends EventEmitter {
220214
if (this._state !== 'init') {
221215
throw new Error('Not in init phase.');
222216
}
223-
this.debug('Initializing replica set.');
217+
log('Initializing replica set.');
224218
if (!this.servers.length) {
225219
throw new Error('One or more server is required.');
226220
}
@@ -264,10 +258,10 @@ export default class MongoMemoryReplSet extends EventEmitter {
264258
},
265259
};
266260
await this.admin.command({ replSetInitiate: rsConfig });
267-
this.debug('Waiting for replica set to have a PRIMARY member.');
261+
log('Waiting for replica set to have a PRIMARY member.');
268262
await this._waitForPrimary();
269263
this.emit((this._state = 'running'));
270-
this.debug('running');
264+
log('running');
271265
} finally {
272266
await conn.close();
273267
}
@@ -276,7 +270,6 @@ export default class MongoMemoryReplSet extends EventEmitter {
276270
_initServer(instanceOpts: MongoMemoryInstancePropT): MongoMemoryServer {
277271
const serverOpts: MongoMemoryServerOptsT = {
278272
autoStart: false,
279-
debug: this.opts.debug,
280273
binary: this.opts.binary,
281274
instance: instanceOpts,
282275
spawn: this.opts.replSet.spawn,
@@ -308,6 +301,6 @@ export default class MongoMemoryReplSet extends EventEmitter {
308301
clearTimeout(timeoutId);
309302
}
310303

311-
this.debug('_waitForPrimary detected one primary instance ');
304+
log('_waitForPrimary detected one primary instance ');
312305
}
313306
}

0 commit comments

Comments
 (0)