Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add log level to handle crash #44

Merged
merged 2 commits into from
May 22, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Node
/node_modules
/*.log

/coverage
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com) and this project follows the [Semantic Versioning](http://semver.org) code.

## 0.5.0 - 2017-04-28
### Added
- Add log level w/o breaking change

### Changed
- Transform current behavior to use strict log level

## 0.4.0 - 2017-04-04
### Changed
- Remove failed status **Breaking change**
Expand Down
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,36 @@ var config = {
}
```

#### logLevel
- Type: `String`
- Default: `strict`
- Allowed value: `strict`, `log`, `none`
- `strict`: catch errors in an exception, **the webpack build crashes**
- `log`: log errors in a log file (`warning.log`) and none behavior
- `none`: show errors in console (when silent mode is off)

Specify behavior when the plugin fail.

Example:
```javascript
var config = {
plugins: [
new ContentReplacerWebpackPlugin({
modifiedFile: './build/index.html',
[
{
regex: /text/g,
modification: 'new text'
}
],
buildTrigger: 'done',
logLevel: 'log'
...
})
]
}
```

#### silent
- Type: `Boolean`
- Default: `false`
Expand Down
60 changes: 60 additions & 0 deletions helpers/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
'use strict';

const winston = require('winston');
const path = require('path');

const createLogger = (level, exception, file, exit) => {
const loggerConfig = {
transports: [
new winston.transports.Console({
level,
handleExceptions: exception,
humanReadableUnhandledException: true,
json: false,
colorize: true,
}),
],
exitOnError: exit,
};
if (file) {
loggerConfig.transports.push(new winston.transports.File({
level,
filename: path.join(__dirname, '/../warning.log'),
handleExceptions: exception,
json: false,
}));
}

return new winston.Logger(loggerConfig);
};

module.exports = (level) => {
if (level === undefined) {
return { warn: () => {} };
}

const exceptionLevel = level.toLowerCase();
let logger;
switch (exceptionLevel) {
case 'none':

// level, exception, file, exit
logger = createLogger('warn', true, false, false);
break;

case 'log':

// level, exception, file, exit
logger = createLogger('warn', true, true, false);
break;

case 'strict':
default:

// level, exception, file, exit
logger = createLogger('error', false, false, true);
break;
}

return logger;
};
26 changes: 25 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const fs = require('fs');
const logger = require('./helpers/logger');

const validBuildTrigger = ['after-emit', 'done'];

Expand All @@ -14,12 +15,20 @@ module.exports = class ContentReplacerWebpackPlugin {
this.buildTrigger = options.buildTrigger || 'after-emit';
this.silent = options.silent === true || false;
this.verbose = !this.silent;

this.logLevel = options.logLevel || 'strict';
this.addLogger();
} else {
// Throw exception
const error = typeof options === 'object'
? 'Required parameters are missing'
: 'Parameters are invalid';

this.silent = false;
this.logLevel = 'strict';
this.addLogger();
this.exceptionLogger.warn(error);

throw new Error(error);
}
}
Expand All @@ -41,6 +50,15 @@ module.exports = class ContentReplacerWebpackPlugin {
options.modifications.length > 0);
}

addLogger() {
if (!this.silent) {
this.exceptionLogger = logger(this.logLevel);
} else {
// Empty logger when silent mode is activated
this.exceptionLogger = logger();
}
}

replace() {
const that = this;
if (fs.existsSync(this.modifiedFile)) {
Expand All @@ -60,7 +78,13 @@ module.exports = class ContentReplacerWebpackPlugin {
return true;
}

throw new Error('File not found');
this.exceptionLogger.warn('File not found');

if (this.logLevel === 'strict') {
throw new Error('File not found');
}

return false;
}

apply(compiler) {
Expand Down
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "webpack-content-replacer-plugin",
"version": "0.4.0",
"version": "0.5.0",
"description": "Replace content in file in webpack workflow",
"main": "index.js",
"scripts": {
Expand Down Expand Up @@ -42,6 +42,7 @@
"expect.js": "^0.3.1",
"istanbul": "^0.4.5",
"mocha": "^3.2.0",
"rimraf": "^2.6.1",
"webpack": "^1.14.0",
"webpack-mock": "^0.1.1"
},
Expand All @@ -53,5 +54,8 @@
},
"files": [
"index.js"
]
],
"dependencies": {
"winston": "^2.3.1"
}
}
65 changes: 65 additions & 0 deletions test/error-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
'use strict';

const fs = require('fs');
const path = require('path');
const expect = require('expect.js');
const webpack = require('webpack');
const except = require('./../workflow_test/webpack.error.config.js');

let stat;
let error;
let compiler = webpack(except.noFileLogLevelOptions);

/**
***************************************************************************
* Log level
***************************************************************************
*/

describe('Webpack workflow log handler test case', function testcase() {
this.timeout(50000);

before((done) => {
compiler.run((err, stats) => {
stat = stats;
error = err;

return done();
});
});

it('should return error in log level', () => {
expect(error).to.equal(null);
expect(stat).to.not.be.empty();
fs.readFile(path.join(__dirname, '../warning.log'), (readError, data) => {
expect(readError).to.be.equal(null);
expect(data.toString('utf8')).to.not.be.empty();
});
});
});

/**
***************************************************************************
* None level
***************************************************************************
*/

compiler = webpack(except.noFileNoneLevelOptions);

describe('Webpack workflow none exception handler test case', function testcase() {
this.timeout(50000);

before((done) => {
compiler.run((err, stats) => {
stat = stats;
error = err;

return done();
});
});

it('should return error in none level', () => {
expect(error).to.equal(null);
expect(stat).to.not.be.empty();
});
});
32 changes: 27 additions & 5 deletions test/module-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,34 @@ describe('ContentReplacer plugin', () => {
expect(ContentReplacerWebpackPlugin.hasRequiredParameters(invalidOptionsObj)).to.equal(false);
});

it('should detect missing file', () => {
contentReplacer.verbose = false;
expect(contentReplacer.replace).to.throwException(/File not found/);
it('should detect missing file in silent mode', () => {
const modifiedOptions = options;
modifiedOptions.silent = true;
contentReplacer = new ContentReplacerWebpackPlugin(modifiedOptions);

let errEx;
try {
contentReplacer.replace();
} catch (e) {
errEx = e;
}

expect(errEx).not.to.be(undefined);
});

contentReplacer.verbose = true;
expect(contentReplacer.replace).to.throwException(/File not found/);
it('should detect missing file in verbose mode', () => {
const modifiedOptions = options;
modifiedOptions.silent = false;
contentReplacer = new ContentReplacerWebpackPlugin(modifiedOptions);

let errEx;
try {
contentReplacer.replace();
} catch (e) {
errEx = e;
}

expect(errEx).not.to.be(undefined);
});

it('should replace content', () => {
Expand Down
36 changes: 36 additions & 0 deletions workflow_test/webpack.error.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const ContentReplacer = require('../index');

const noFileNoneLevelOptions = {
modifiedFile: '/somepath',
modifications: [
{
regex: /red/g,
modification: 'blue',
},
],
logLevel: 'none',
};

const noFileLogLevelOptions = {
modifiedFile: '/somepath',
modifications: [
{
regex: /red/g,
modification: 'blue',
},
],
logLevel: 'log',
};

module.exports = {
noFileNoneLevelOptions: {
plugins: [
new ContentReplacer(noFileNoneLevelOptions),
],
},
noFileLogLevelOptions: {
plugins: [
new ContentReplacer(noFileLogLevelOptions),
],
},
};