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

Debug logging toggle via global boolean #2282

Merged
merged 4 commits into from
Nov 21, 2019
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
11 changes: 9 additions & 2 deletions infra/testing/validator/service-worker-runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ function setupSpiesAndContextForGenerateSW() {
return {addEventListener, context, methodsToSpies: workboxContext};
}

function validateMethodCalls({methodsToSpies, expectedMethodCalls}) {
function validateMethodCalls({methodsToSpies, expectedMethodCalls, context}) {
for (const [method, spy] of Object.entries(methodsToSpies)) {
if (spy.called) {
// Special-case handling for importScripts(), as the first call may be
Expand All @@ -157,6 +157,13 @@ function validateMethodCalls({methodsToSpies, expectedMethodCalls}) {
`while testing method calls for ${method}`).to.be.undefined;
}
}

// Special validation for __WB_DISABLE_DEV_LOGS, which is a boolean
// assignment, so we can't stub it out.
if ('__WB_DISABLE_DEV_LOGS' in expectedMethodCalls) {
expect(context.self.__WB_DISABLE_DEV_LOGS).to.eql(
expectedMethodCalls.__WB_DISABLE_DEV_LOGS, `__WB_DISABLE_DEV_LOGS`);
}
}

/**
Expand Down Expand Up @@ -194,7 +201,7 @@ module.exports = async ({

vm.runInNewContext(swString, context);

validateMethodCalls({methodsToSpies, expectedMethodCalls});
validateMethodCalls({methodsToSpies, expectedMethodCalls, context});

// Optionally check the usage of addEventListener().
if (addEventListenerValidation) {
Expand Down
2 changes: 2 additions & 0 deletions packages/workbox-build/src/lib/populate-sw-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ module.exports = ({
cleanupOutdatedCaches,
clientsClaim,
directoryIndex,
disableDevLogs,
ignoreURLParametersMatching,
importScripts,
manifestEntries = [],
Expand Down Expand Up @@ -73,6 +74,7 @@ module.exports = ({
cacheId,
cleanupOutdatedCaches,
clientsClaim,
disableDevLogs,
importScripts,
manifestEntries,
navigateFallback,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ module.exports = async ({
cleanupOutdatedCaches,
clientsClaim,
directoryIndex,
disableDevLogs,
ignoreURLParametersMatching,
importScripts,
inlineWorkboxRuntime,
Expand Down Expand Up @@ -47,6 +48,7 @@ module.exports = async ({
cleanupOutdatedCaches,
clientsClaim,
directoryIndex,
disableDevLogs,
ignoreURLParametersMatching,
importScripts,
manifestEntries,
Expand Down
1 change: 1 addition & 0 deletions packages/workbox-build/src/options/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ module.exports = {
babelPresetEnvTargets: ['chrome >= 56'],
cleanupOutdatedCaches: false,
clientsClaim: false,
disableDevLogs: false,
exclude: [
/\.map$/,
/^manifest.*\.js$/,
Expand Down
1 change: 1 addition & 0 deletions packages/workbox-build/src/options/partials/generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ module.exports = {
cleanupOutdatedCaches: joi.boolean().default(defaults.cleanupOutdatedCaches),
clientsClaim: joi.boolean().default(defaults.clientsClaim),
directoryIndex: joi.string(),
disableDevLogs: joi.boolean().default(defaults.disableDevLogs),
ignoreURLParametersMatching: joi.array().items(regExpObject),
importScripts: joi.array().items(joi.string()),
inlineWorkboxRuntime: joi.boolean().default(defaults.inlineWorkboxRuntime),
Expand Down
4 changes: 3 additions & 1 deletion packages/workbox-build/src/templates/sw-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,6 @@ self.addEventListener('message', (event) => {

<% if (runtimeCaching) { runtimeCaching.forEach(runtimeCachingString => {%><%= runtimeCachingString %><% });} %>

<% if (offlineAnalyticsConfigString) { %><%= use('workbox-google-analytics', 'initialize') %>(<%= offlineAnalyticsConfigString %>);<% } %>`;
<% if (offlineAnalyticsConfigString) { %><%= use('workbox-google-analytics', 'initialize') %>(<%= offlineAnalyticsConfigString %>);<% } %>

<% if (disableDevLogs) { %>self.__WB_DISABLE_DEV_LOGS = true;<% } %>`;
12 changes: 11 additions & 1 deletion packages/workbox-core/src/_private/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,17 @@

import '../_version.js';

declare global {
interface WorkerGlobalScope {
__WB_DISABLE_DEV_LOGS: boolean;
}
}

type LoggerMethods = 'debug'|'log'|'warn'|'error'|'groupCollapsed'|'groupEnd';


const logger = <Console> (process.env.NODE_ENV === 'production' ? null : (() => {
self.__WB_DISABLE_DEV_LOGS = false;

let inGroup = false;

const methodToColorMap: {[methodName: string]: string|null} = {
Expand All @@ -24,6 +30,10 @@ const logger = <Console> (process.env.NODE_ENV === 'production' ? null : (() =>
};

const print = function(method: LoggerMethods, args: any[]) {
if (self.__WB_DISABLE_DEV_LOGS) {
return;
}

if (method === 'groupCollapsed') {
// Safari doesn't print all console.groupCollapsed() arguments:
// https://bugs.webkit.org/show_bug.cgi?id=182754
Expand Down
42 changes: 42 additions & 0 deletions test/workbox-build/node/generate-sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() {
'cacheId',
'clientsClaim',
'directoryIndex',
'disableDevLogs',
'dontCacheBustURLsMatching',
'globDirectory',
'globFollow',
Expand Down Expand Up @@ -138,6 +139,47 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() {
confirmDirectoryContains(outputDir, filePaths);

await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: {
__WB_DISABLE_DEV_LOGS: undefined,
importScripts: [],
precacheAndRoute: [[[{
url: 'index.html',
revision: '3883c45b119c9d7e9ad75a1b4a4672ac',
}, {
url: 'page-1.html',
revision: '544658ab25ee8762dc241e8b1c5ed96d',
}, {
url: 'page-2.html',
revision: 'a3a71ce0b9b43c459cf58bd37e911b74',
}, {
url: 'styles/stylesheet-1.css',
revision: '934823cbc67ccf0d67aa2a2eeb798f12',
}, {
url: 'styles/stylesheet-2.css',
revision: '884f6853a4fc655e4c2dc0c0f27a227c',
}, {
url: 'webpackEntry.js',
revision: '5b652181a25e96f255d0490203d3c47e',
}], {}]],
}});
});

it(`should disable logging when disableDevLogs is set to true`, async function() {
const outputDir = tempy.directory();
const swDest = upath.join(outputDir, 'sw.js');
const options = Object.assign({}, BASE_OPTIONS, {
disableDevLogs: true,
swDest,
});

const {count, filePaths, size, warnings} = await generateSW(options);
expect(warnings).to.be.empty;
expect(count).to.eql(6);
expect(size).to.eql(2604);

confirmDirectoryContains(outputDir, filePaths);

await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: {
__WB_DISABLE_DEV_LOGS: true,
importScripts: [],
precacheAndRoute: [[[{
url: 'index.html',
Expand Down
5 changes: 5 additions & 0 deletions test/workbox-build/node/lib/populate-sw-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() {
cacheId: undefined,
cleanupOutdatedCaches: undefined,
clientsClaim: undefined,
disableDevLogs: undefined,
importScripts: undefined,
navigateFallback: undefined,
navigateFallbackBlacklist: undefined,
Expand All @@ -89,6 +90,7 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() {
const cleanupOutdatedCaches = true;
const clientsClaim = true;
const directoryIndex = 'index.html';
const disableDevLogs = true;
const handleFetch = true;
const ignoreURLParametersMatching = [/a/, /b/];
const importScripts = ['test.js'];
Expand Down Expand Up @@ -122,6 +124,7 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() {
cleanupOutdatedCaches,
clientsClaim,
directoryIndex,
disableDevLogs,
handleFetch,
ignoreURLParametersMatching,
importScripts,
Expand All @@ -145,6 +148,7 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() {
cacheId,
cleanupOutdatedCaches,
clientsClaim,
disableDevLogs,
importScripts,
manifestEntries,
navigateFallback,
Expand Down Expand Up @@ -195,6 +199,7 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() {
cacheId: undefined,
cleanupOutdatedCaches: undefined,
clientsClaim: undefined,
disableDevLogs: undefined,
importScripts: undefined,
navigateFallback: undefined,
navigateFallbackBlacklist: undefined,
Expand Down
16 changes: 16 additions & 0 deletions test/workbox-core/sw/_private/test-logger.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ describe(`logger`, function() {
}
});
}

self.__WB_DISABLE_DEV_LOGS = false;
});

after(function() {
Expand Down Expand Up @@ -59,6 +61,20 @@ describe(`logger`, function() {
expect(logger).to.equal(null);
});

it(`should toggle logging based on the value of __WB_DISABLE_DEV_LOGS`, function() {
if (process.env.NODE_ENV === 'production') this.skip();

const logStub = sandbox.stub(console, 'log');

self.__WB_DISABLE_DEV_LOGS = true;
logger.log('');
expect(logStub.callCount).to.eql(0);

self.__WB_DISABLE_DEV_LOGS = false;
logger.log('');
expect(logStub.callCount).to.eql(1);
});

consoleLevels.forEach((consoleLevel) => {
describe(`.${consoleLevel}()`, function() {
it(`should work without input`, function() {
Expand Down