Skip to content

Commit f0534fc

Browse files
committed
Use webpack-log for logging
webpack-dev-middleware already uses this, should not be breaking unless you rely on WDS's exact output format.
1 parent f76182c commit f0534fc

File tree

6 files changed

+66
-41
lines changed

6 files changed

+66
-41
lines changed

bin/webpack-dev-server.js

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ const open = require('opn');
1414
const portfinder = require('portfinder');
1515
const addDevServerEntrypoints = require('../lib/util/addDevServerEntrypoints');
1616
const createDomain = require('../lib/util/createDomain'); // eslint-disable-line
17+
const createLog = require('../lib/createLog');
1718

1819
// Prefer the local installation of webpack-dev-server
1920
if (importLocal(__filename)) {
@@ -370,14 +371,15 @@ function processOptions(webpackOptions) {
370371
}
371372

372373
function startDevServer(webpackOptions, options) {
374+
const log = createLog(options);
373375
addDevServerEntrypoints(webpackOptions, options);
374376

375377
let compiler;
376378
try {
377379
compiler = webpack(webpackOptions);
378380
} catch (e) {
379381
if (e instanceof webpack.WebpackOptionsValidationError) {
380-
console.error(colorError(options.stats.colors, e.message));
382+
log.error(colorError(options.stats.colors, e.message));
381383
process.exit(1); // eslint-disable-line
382384
}
383385
throw e;
@@ -393,11 +395,11 @@ function startDevServer(webpackOptions, options) {
393395

394396
let server;
395397
try {
396-
server = new Server(compiler, options);
398+
server = new Server(compiler, options, log);
397399
} catch (e) {
398400
const OptionsValidationError = require('../lib/OptionsValidationError');
399401
if (e instanceof OptionsValidationError) {
400-
console.error(colorError(options.stats.colors, e.message));
402+
log.error(colorError(options.stats.colors, e.message));
401403
process.exit(1); // eslint-disable-line
402404
}
403405
throw e;
@@ -437,7 +439,7 @@ function startDevServer(webpackOptions, options) {
437439
if (fsError) throw fsError;
438440

439441
const uri = createDomain(options, server.listeningApp) + suffix;
440-
reportReadiness(uri, options);
442+
reportReadiness(uri, options, log);
441443
});
442444
});
443445
} else {
@@ -446,31 +448,28 @@ function startDevServer(webpackOptions, options) {
446448
if (options.bonjour) broadcastZeroconf(options);
447449

448450
const uri = createDomain(options, server.listeningApp) + suffix;
449-
reportReadiness(uri, options);
451+
reportReadiness(uri, options, log);
450452
});
451453
}
452454
}
453455

454-
function reportReadiness(uri, options) {
456+
function reportReadiness(uri, options, log) {
455457
const useColor = argv.color;
456458
const contentBase = Array.isArray(options.contentBase) ? options.contentBase.join(', ') : options.contentBase;
457459

458-
if (!options.quiet) {
459-
let startSentence = `Project is running at ${colorInfo(useColor, uri)}`;
460-
if (options.socket) {
461-
startSentence = `Listening to socket at ${colorInfo(useColor, options.socket)}`;
462-
}
463-
464-
console.log((options.progress ? '\n' : '') + startSentence);
460+
if (options.socket) {
461+
log.info(`Listening to socket at ${colorInfo(useColor, options.socket)}`);
462+
} else {
463+
log.info(`Project is running at ${colorInfo(useColor, uri)}`);
464+
}
465465

466-
console.log(`webpack output is served from ${colorInfo(useColor, options.publicPath)}`);
466+
log.info(`webpack output is served from ${colorInfo(useColor, options.publicPath)}`);
467467

468-
if (contentBase) { console.log(`Content not from webpack is served from ${colorInfo(useColor, contentBase)}`); }
468+
if (contentBase) { log.info(`Content not from webpack is served from ${colorInfo(useColor, contentBase)}`); }
469469

470-
if (options.historyApiFallback) { console.log(`404s will fallback to ${colorInfo(useColor, options.historyApiFallback.index || '/index.html')}`); }
470+
if (options.historyApiFallback) { log.info(`404s will fallback to ${colorInfo(useColor, options.historyApiFallback.index || '/index.html')}`); }
471471

472-
if (options.bonjour) { console.log('Broadcasting "http" with subtype of "webpack" via ZeroConf DNS (Bonjour)'); }
473-
}
472+
if (options.bonjour) { log.info('Broadcasting "http" with subtype of "webpack" via ZeroConf DNS (Bonjour)'); }
474473

475474
if (options.open) {
476475
let openOptions = {};
@@ -482,7 +481,7 @@ function reportReadiness(uri, options) {
482481
}
483482

484483
open(uri + (options.openPage || ''), openOptions).catch(() => {
485-
console.log(`${openMessage}. If you are running in a headless environment, please do not use the open flag.`);
484+
log.warn(`${openMessage}. If you are running in a headless environment, please do not use the open flag.`);
486485
});
487486
}
488487
}

lib/Server.js

Lines changed: 16 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,16 @@ const sockjs = require('sockjs');
2121
const spdy = require('spdy');
2222
const webpack = require('webpack');
2323
const webpackDevMiddleware = require('webpack-dev-middleware');
24+
const createLog = require('./createLog');
2425
const OptionsValidationError = require('./OptionsValidationError');
2526
const optionsSchema = require('./optionsSchema.json');
2627

2728
const clientStats = { errorDetails: false };
28-
const log = console.log; // eslint-disable-line no-console
2929

30-
function Server(compiler, options) {
30+
function Server(compiler, options, _log) {
3131
// Default options
3232
if (!options) options = {};
33+
this.log = _log || createLog(options);
3334

3435
const validationErrors = webpack.validateSchema(optionsSchema, options);
3536
if (validationErrors.length) {
@@ -88,14 +89,8 @@ function Server(compiler, options) {
8889
res.send('Invalid Host header');
8990
});
9091

91-
const wdmOptions = {};
92+
const wdmOptions = { logLevel: this.log.options.level };
9293

93-
if (options.quiet === true) {
94-
wdmOptions.logLevel = 'silent';
95-
}
96-
if (options.noInfo === true) {
97-
wdmOptions.logLevel = 'warn';
98-
}
9994
// middleware for serving webpack bundle
10095
this.middleware = webpackDevMiddleware(compiler, Object.assign({}, options, wdmOptions));
10196

@@ -286,14 +281,14 @@ function Server(compiler, options) {
286281
}
287282
},
288283

289-
contentBaseFiles() {
284+
contentBaseFiles: () => {
290285
if (Array.isArray(contentBase)) {
291286
contentBase.forEach((item) => {
292287
app.get('*', express.static(item));
293288
});
294289
} else if (/^(https?:)?\/\//.test(contentBase)) {
295-
log('Using a URL as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.');
296-
log('proxy: {\n\t"*": "<your current contentBase configuration>"\n}'); // eslint-disable-line quotes
290+
this.log.warn('Using a URL as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.');
291+
this.log.warn('proxy: {\n\t"*": "<your current contentBase configuration>"\n}'); // eslint-disable-line quotes
297292
// Redirect every request to contentBase
298293
app.get('*', (req, res) => {
299294
res.writeHead(302, {
@@ -302,8 +297,8 @@ function Server(compiler, options) {
302297
res.end();
303298
});
304299
} else if (typeof contentBase === 'number') {
305-
log('Using a number as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.');
306-
log('proxy: {\n\t"*": "//localhost:<your current contentBase configuration>"\n}'); // eslint-disable-line quotes
300+
this.log.warn('Using a number as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.');
301+
this.log.warn('proxy: {\n\t"*": "//localhost:<your current contentBase configuration>"\n}'); // eslint-disable-line quotes
307302
// Redirect every request to the port contentBase
308303
app.get('*', (req, res) => {
309304
res.writeHead(302, {
@@ -364,7 +359,7 @@ function Server(compiler, options) {
364359

365360
setup: () => {
366361
if (typeof options.setup === 'function') {
367-
log('The `setup` option is deprecated and will be removed in v3. Please update your config to use `before`');
362+
this.log.warn('The `setup` option is deprecated and will be removed in v3. Please update your config to use `before`');
368363
options.setup(app, this);
369364
}
370365
}
@@ -415,14 +410,14 @@ function Server(compiler, options) {
415410

416411
// cert is more than 30 days old, kill it with fire
417412
if ((now - certStat.ctime) / certTtl > 30) {
418-
log('SSL Certificate is more than 30 days old. Removing.');
413+
this.log.info('SSL Certificate is more than 30 days old. Removing.');
419414
del.sync([certPath], { force: true });
420415
certExists = false;
421416
}
422417
}
423418

424419
if (!certExists) {
425-
log('Generating SSL Certificate');
420+
this.log.info('Generating SSL Certificate');
426421
const attrs = [{ name: 'commonName', value: 'localhost' }];
427422
const pems = selfsigned.generate(attrs, {
428423
algorithm: 'sha256',
@@ -573,16 +568,16 @@ Server.prototype.checkHost = function (headers) {
573568
// delegate listen call and init sockjs
574569
Server.prototype.listen = function (port, hostname, fn) {
575570
this.listenHostname = hostname;
576-
// eslint-disable-next-line
577-
578571
const returnValue = this.listeningApp.listen(port, hostname, (err) => {
579572
const sockServer = sockjs.createServer({
580573
// Use provided up-to-date sockjs-client
581574
sockjs_url: '/__webpack_dev_server__/sockjs.bundle.js',
582575
// Limit useless logs
583-
log(severity, line) {
576+
log: (severity, line) => {
584577
if (severity === 'error') {
585-
log(line);
578+
this.log.error(line);
579+
} else {
580+
this.log.debug(line);
586581
}
587582
}
588583
});

lib/createLog.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
'use strict';
2+
3+
const weblog = require('webpack-log');
4+
5+
module.exports = function createLog(options) {
6+
let logLevel = options.logLevel || 'info';
7+
if (options.quiet === true) {
8+
logLevel = 'silent';
9+
}
10+
if (options.noInfo === true) {
11+
logLevel = 'warn';
12+
}
13+
14+
return weblog({
15+
level: logLevel,
16+
name: 'wds',
17+
timestamp: options.logTime
18+
});
19+
};

lib/optionsSchema.json

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,17 @@
6666
"description": "Response headers that are added to each response.",
6767
"type": "object"
6868
},
69+
"logLevel": {
70+
"description": "Log level in the terminal/console (trace, debug, info, warn, error or none)",
71+
"enum": [
72+
"trace",
73+
"debug",
74+
"info",
75+
"warn",
76+
"error",
77+
"none"
78+
]
79+
},
6980
"clientLogLevel": {
7081
"description": "Controls the log messages shown in the browser.",
7182
"enum": [

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
"strip-ansi": "^3.0.0",
6969
"supports-color": "^5.1.0",
7070
"webpack-dev-middleware": "2.0.6",
71+
"webpack-log": "^1.1.2",
7172
"yargs": "9.0.1"
7273
},
7374
"devDependencies": {

test/Validation.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ describe('Validation', () => {
4949
message: [
5050
" - configuration has an unknown property 'asdf'. These properties are valid:",
5151
' object { hot?, hotOnly?, lazy?, bonjour?, host?, allowedHosts?, filename?, publicPath?, port?, socket?, ' +
52-
'watchOptions?, headers?, clientLogLevel?, overlay?, progress?, key?, cert?, ca?, pfx?, pfxPassphrase?, requestCert?, ' +
52+
'watchOptions?, headers?, logLevel?, clientLogLevel?, overlay?, progress?, key?, cert?, ca?, pfx?, pfxPassphrase?, requestCert?, ' +
5353
'inline?, disableHostCheck?, public?, https?, contentBase?, watchContentBase?, open?, useLocalIp?, openPage?, features?, ' +
5454
'compress?, proxy?, historyApiFallback?, staticOptions?, setup?, before?, after?, stats?, reporter?, logTime?, ' +
5555
'noInfo?, quiet?, serverSideRender?, index?, log?, warn? }'

0 commit comments

Comments
 (0)