Skip to content

Instantly share code, notes, and snippets.

@cwparsons
Last active July 10, 2018 23:52
Show Gist options
  • Save cwparsons/776602a7d92b1056801800a3000f7ed1 to your computer and use it in GitHub Desktop.
Save cwparsons/776602a7d92b1056801800a3000f7ed1 to your computer and use it in GitHub Desktop.
Capture telemetry data within a gulp task.

We use the following to track gulp tasks in Google Analytics.

const gulp = require('gulp');
const telemetry = require('./telemetry');
// A simple task that runs relatively quickly.
gulp.task('Simple task', () => {
telemetry('Gulp', 'Task run', 'Simple task');
return gulp.src()
.pipe(gulp.dest());
});
// A complex task that may error out.
gulp.task('Complex task', () => {
telemetry('Gulp', 'Task run', 'Complex task');
return gulp.src()
.pipe(gulp.dest())
.on('error', () => {
telemetry('Gulp', 'Task error', 'Complex task.');
})
.on('end', () => {
telemetry('Gulp', 'Task end', 'Complex task');
});
});
// A long task that wher duration needs to be tracked.
gulp.task('Long task', () => {
telemetry('Gulp', 'Task run', 'Complex task');
const now = new Date().getTime() / 1000;
return gulp.src()
.pipe(/* An operation that might take a long time. */)
.pipe(gulp.dest())
.on('end', () => {
const duration = Math.round((new Date().getTime() / 1000) - now);
telemetry('Gulp', 'Task end', 'Long task', duration);
});
});
{
"devDependencies": {
"gulp": "3.9.1",
"gulp-util": "3.0.8",
"universal-analytics": "0.4.17"
}
}
module.exports = function (eventCategory, eventAction, eventLabel = null, eventValue = null) {
const config = require('./config')();
const gutil = require('gulp-util');
const os = require('os');
const ua = require('universal-analytics');
const telemetryAnalyticsId = 'UA-XXXYYY';
// Instead of creating a visitor GUID, we try sending the hostname of the computer.
const visitor = ua(telemetryAnalyticsId, os.hostname(), { strictCidFormat: false });
if (eventLabel && eventValue && !isNaN(eventValue)) {
visitor.event(eventCategory, eventAction, eventLabel, eventValue).send();
gutil.log('Telemetry sent:', eventCategory, eventAction, eventLabel, eventValue);
} else if (eventLabel) {
visitor.event(eventCategory, eventAction, eventLabel).send();
gutil.log('Telemetry sent:', eventCategory, eventAction, eventLabel);
} else {
visitor.event(eventCategory, eventAction).send();
gutil.log('Telemetry sent:', eventCategory, eventAction);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment