forked from brutaldev/logfile-grunt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogfile-grunt.js
70 lines (58 loc) · 1.9 KB
/
logfile-grunt.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* logfile-grunt
* https://github.com/brutaldev/logfile-grunt
*
* Copyright (c) 2015 Werner van Deventer
* Licensed under the MIT license.
*/
'use strict';
var hooker = require('hooker');
var hook = new (require('events').EventEmitter)();
// Hook the stdout.write function.
hooker.hook(process.stdout, 'write', {
pre: hook.emit.bind(hook, 'write')
});
// Hook the stderr.write function.
hooker.hook(process.stderr, 'write', {
pre: hook.emit.bind(hook, 'write')
});
process.on('exit', function () {
hook.removeAllListeners();
hooker.unhook(process.stdout, 'write');
hooker.unhook(process.stderr, 'write');
});
module.exports = function (grunt, options) {
var fs = require('fs');
// Honor the no-write option.
var nowrite = grunt.option('no-write');
// Validate parameters and set to defaults.
options = options || {};
options.filePath = (options.filePath || './logs/grunt.log').replace(/\\/g, '/');
options.clearLogFile = !!options.clearLogFile || false;
options.keepColors = !!options.keepColors || false;
options.textEncoding = options.textEncoding || 'utf-8';
if (!nowrite)
{
grunt.log.writeln('Grunt and task output will also be logged to "' + options.filePath + '"');
// Create the file if it does not exist, Grunt creates the directories and everything for us.
if (!grunt.file.exists(options.filePath)) {
grunt.file.write(options.filePath, '', {
encoding: options.textEncoding
});
}
// Clear the log file if requested.
if (options.clearLogFile) {
grunt.file.write(options.filePath, '', {
encoding: options.textEncoding
});
}
}
hook.on('write', function (result) {
if (result && !nowrite) {
var output = result.toString();
fs.appendFileSync(options.filePath, grunt.util.normalizelf(options.keepColors ? output : grunt.log.uncolor(output)), {
encoding: options.textEncoding
});
}
});
};