Skip to content

Commit

Permalink
♻️ Use scoped loggers (ampproject#3526)
Browse files Browse the repository at this point in the history
* ♻️ Refactor to use scoped loggers

* ♻️ Refactor to use scoped loggers

* 🐛 Fix scope in platform.js

* ♻️ Fix lint errors

* 👌 Fix scopes

* 👌 Update scope

* 👌 Adapt log messages

* 🚨 Fix lint error
  • Loading branch information
robinvanopstal authored Feb 18, 2020
1 parent 118bbda commit e155fd8
Show file tree
Hide file tree
Showing 21 changed files with 103 additions and 82 deletions.
3 changes: 2 additions & 1 deletion boilerplate/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const path = require('path');

const io = require('./lib/io');
const templates = require('./lib/templates');
const log = require('@lib/utils/log')('Build Boilerplate');

const DIST_DIR = 'dist';
const INPUT_FILE = 'templates/index.html';
Expand All @@ -29,7 +30,7 @@ const generatorTemplate = io.readFile(INPUT_FILE);
const config = initConfig();
const generatorPage = templates.render(generatorTemplate, config);
generateOptimizedAmpFiles(generatorPage);
console.log('Built boilerplate generator.');
log.success('Built boilerplate generator.');

function initConfig() {
const config = {
Expand Down
3 changes: 2 additions & 1 deletion examples/lib/SampleRenderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const {join} = require('path');
const utils = require('@lib/utils');
const {Templates} = require('@lib/templates/index.js');
const config = require('@lib/config.js');
const log = require('@lib/utils/log')('Sample Renderer');
const fetch = require('node-fetch');
const {promisify} = require('util');

Expand Down Expand Up @@ -71,7 +72,7 @@ class SampleRenderer {
const template = await this.getTemplate_(request);
handler(request, response, template);
} catch (err) {
console.log(err);
log.error(err);
next(err);
}
};
Expand Down
9 changes: 6 additions & 3 deletions gulpfile.js/import.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const emojiStrip = require('emoji-strip');
const {promisify} = require('util');
const writeFileAsync = promisify(fs.writeFile);
const {GitHubImporter} = require('@lib/pipeline/gitHubImporter');
const log = require('@lib/utils/log')('Import Working Groups');

/* The GitHub organisation the repositories imported from are located */
const WG_GH_ORGANISATION = 'ampproject';
Expand All @@ -36,6 +37,8 @@ async function importWorkingGroups() {
await client._github.org(WG_GH_ORGANISATION).reposAsync(1, 100)
)[0];

log.start('Start importing Working Groups..');

for (const wg of repos) {
if (!wg.name.startsWith('wg-')) {
continue;
Expand All @@ -48,13 +51,13 @@ async function importWorkingGroups() {
.repo(`${WG_GH_ORGANISATION}/${wg.name}`)
.contentsAsync('METADATA.yaml');
} catch (e) {
console.warn(`No METADATA.yaml for working group ${wg.name}`);
log.warn(`No METADATA.yaml for working group ${wg.name}`);
continue;
}
try {
meta = yaml.safeLoad(Buffer.from(meta[0].content, 'base64').toString());
} catch (e) {
console.error(
log.error(
`Failed loading ${WG_GH_ORGANISATION}/${wg.name}/METADATA.yaml`,
e
);
Expand Down Expand Up @@ -109,7 +112,7 @@ async function importWorkingGroups() {
})
);

console.log('Imported working group data', wg.name);
log.success('Imported working group data for:', wg.name);
}
}

Expand Down
3 changes: 2 additions & 1 deletion platform/lib/middleware/redirects.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const yaml = require('js-yaml');
const config = require('@lib/config.js');
const {setHsts} = require('@lib/utils/cacheHelpers.js');
const {HEALTH_CHECK_PATH} = require('@lib/routers/healthCheck.js');
const log = require('@lib/utils/log')('Redirects');

const WWW_PREFIX = 'www.';

Expand Down Expand Up @@ -84,7 +85,7 @@ module.exports = (req, res, next) => {
res.redirect(targetUrl.toString());
return;
} catch (error) {
console.log('Unable to redirect to ' + redirectTarget, error);
log.warn('Unable to redirect to ' + redirectTarget, error);
}
}

Expand Down
10 changes: 2 additions & 8 deletions platform/lib/pipeline/componentReferenceImporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,10 @@ const validatorRules = require('@ampproject/toolbox-validator-rules');

const ComponentReferenceDocument = require('./componentReferenceDocument.js');

const {Signale} = require('signale');

const log = require('@lib/utils/log')('Component Reference Importer');
const config = require(__dirname +
'/../../config/imports/componentReference.json');

const log = new Signale({
'interactive': false,
'scope': 'ComponentReferenceImporter',
});

// Where to save the documents/collection to
const DESTINATION_BASE_PATH =
__dirname +
Expand Down Expand Up @@ -325,7 +319,7 @@ class ComponentReferenceImporter {
// If not required, run directly
if (!module.parent) {
const importer = new ComponentReferenceImporter();
importer.import().catch(err => console.log(err));
importer.import().catch(err => log.error(err));
}

module.exports = ComponentReferenceImporter;
10 changes: 5 additions & 5 deletions platform/lib/platform.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@

'use strict';

const signale = require('signale');
const express = require('express');
const shrinkRay = require('shrink-ray-current');
const cors = require('cors');
const ampCors = require('@ampproject/toolbox-cors');
const config = require('./config.js');
const {pagePath} = require('@lib/utils/project');
const log = require('@lib/utils/log')('Platform');
const subdomain = require('./middleware/subdomain.js');

const routers = {
Expand Down Expand Up @@ -55,12 +55,12 @@ const PORT = config.hosts.platform.port || process.env.APP_PORT || 80;

class Platform {
start() {
signale.info('Starting platform');
log.info('Starting platform');
return new Promise(async (resolve, reject) => {
try {
await this._createServer();
this.httpServer = this.server.listen(PORT, () => {
signale.success(`server listening on ${PORT}!`);
log.success(`server listening on ${PORT}!`);
resolve();
});
// Increase keep alive timeout
Expand All @@ -73,14 +73,14 @@ class Platform {
}

stop() {
signale.info('Stopping platform');
log.info('Stopping platform');
return new Promise(async (resolve, reject) => {
this.httpServer.close(() => resolve());
});
}

async _createServer() {
signale.await(
log.await(
`Starting platform with environment ${config.environment} on ${HOST} ...`
);
this.server = express();
Expand Down
3 changes: 2 additions & 1 deletion platform/lib/routers/go.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
const yaml = require('js-yaml');
const express = require('express');
const config = require('@lib/config.js');
const log = require('@lib/utils/log')('Go Links');
const {join} = require('path');
const {readFileSync} = require('fs');
const URL = require('url').URL;
Expand Down Expand Up @@ -54,7 +55,7 @@ go.use((request, response, next) => {
response.redirect(targetUrl.toString());
return;
} catch (error) {
console.log(error);
log.error(error);
notFound(request, response, next);
}
});
Expand Down
3 changes: 2 additions & 1 deletion platform/lib/routers/growSharedPages.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

const express = require('express');
const {ensureUrlScheme, loadTemplate} = require('./growPages.js');
const log = require('@lib/utils/log')('Grow Shared Pages');

// eslint-disable-next-line new-cap
const sharedPages = express.Router();
Expand All @@ -34,7 +35,7 @@ sharedPages.get('/shared/**', async (req, res, next) => {
res.send(template.render());
} catch (e) {
// page not found
console.error(e);
log.error(e);
next();
}
});
Expand Down
3 changes: 2 additions & 1 deletion platform/lib/routers/healthCheck.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
'use strict';

const express = require('express');
const log = require('@lib/utils/log')('Health Check');

// eslint-disable-next-line new-cap
const healthCheck = express.Router();
Expand All @@ -25,7 +26,7 @@ const HEALTH_CHECK_PATH = '/__health-check';
// Used by GCE to determine wether a VM instance is healthy.
healthCheck.get(HEALTH_CHECK_PATH, (req, res) => {
// TODO add more checks
console.log('[HEALTH CHECK] OK');
log.info('OK');
res.status(200).send('OK');
});

Expand Down
7 changes: 4 additions & 3 deletions platform/lib/routers/packager.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
const HttpProxy = require('http-proxy');
const config = require('@lib/config');
const mime = require('mime-types');
const log = require('@lib/utils/log')('Packager');

const proxyOptions = {
target: config.hosts.packager.base,
Expand Down Expand Up @@ -49,7 +50,7 @@ const packager = (request, response, next) => {
pagesHost += `:${config.hosts.platform.port}`;
}
if (request.get('host') !== pagesHost) {
console.log('[packager] not packaging', request.get('host'), pagesHost);
log.info('Not packaging', request.get('host'), pagesHost);
next();
return;
}
Expand Down Expand Up @@ -83,10 +84,10 @@ const packager = (request, response, next) => {
};

function sxgProxy(request, response, url) {
console.log('[packager] proxy', url);
log.info('Proxy', url);
request.url = url;
proxy.web(request, response, proxyOptions, error => {
console.log('[packager] proxy error', error);
log.info('Proxy error', error);
response.status(502).end();
});
}
Expand Down
3 changes: 2 additions & 1 deletion platform/lib/routers/runtimeLog.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

const express = require('express');
const LogFormatter = require('../runtime-log/HtmlFormatter.js');
const log = require('@lib/utils/log')('Runtime Log');
const robots = require('./robots');

const {Templates} = require('../templates/');
Expand Down Expand Up @@ -48,7 +49,7 @@ runtimeLog.get('/', async (request, response) => {
})
);
} catch (error) {
console.error('retrieving runtime log', error);
log.error('Retrieving runtime log failed:', error);
response.status(404).send('Message not found');
}
});
Expand Down
3 changes: 2 additions & 1 deletion platform/lib/routers/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const project = require('@lib/utils/project.js');
const googleSearch = require('@lib/utils/googleSearch.js');
const samples = require('@lib/common/samples.js');
const {setMaxAge} = require('@lib/utils/cacheHelpers');
const log = require('@lib/utils/log')('Search');
const URL = require('url').URL;

const {
Expand Down Expand Up @@ -277,7 +278,7 @@ async function handleSearchRequest(request, response, next) {
', page=' +
request.query.page +
')';
console.log(error);
log.error(error);
// No error status since an empty query can always happen with our search template
// and we do not want error messages in the client console
response.status(200).json({error: error});
Expand Down
2 changes: 0 additions & 2 deletions platform/lib/samples/DocumentParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,6 @@ class DocumentParser {
this.updateHead(line);
this.updateStory(line);
if (this.endOfCurrentTag(line)) {
// console.log("end tag: " + this.currentTag);
if (this.inHintedElement) {
this.currentSection().endHint();
this.inHintedElement = false;
Expand Down Expand Up @@ -164,7 +163,6 @@ class DocumentParser {
} else if (this.inComment) {
this.inComment = false;
this.currentTag = this.nextTag(i);
// console.log("start tag: " + this.currentTag);
}
}
}
Expand Down
5 changes: 3 additions & 2 deletions platform/lib/samples/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const {promisify} = require('util');
const fs = require('fs');
const Hogan = require('hogan.js');
const readFileAsync = promisify(fs.readFile);
const log = require('@lib/utils/log')('Parse Samples');

module.exports.parseSample = async (filePath, config, contents) => {
if (!contents) {
Expand All @@ -35,10 +36,10 @@ module.exports.parseSample = async (filePath, config, contents) => {
const doc = parse(contents);
const exampleFile = ExampleFile.fromPath(filePath);
if (!doc.title) {
console.warn(`${filePath} has no title`);
log.warn(`${filePath} has no title`);
doc.title = exampleFile.title();
} else if (doc.title !== exampleFile.title()) {
console.warn(
log.warn(
`${filePath} has invalid title: "${exampleFile.title()}" vs "${
doc.title
}"`
Expand Down
3 changes: 2 additions & 1 deletion platform/lib/templates/ImportBlogFilter.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@ const POST_COUNT = 6;
const BLOG_PATH = `https://blog.amp.dev/wp-json/wp/v2/posts?per_page=${POST_COUNT}&_embed`;
const DEFAULT_IMG = 'AMP_Blog_Square.jpg';
const fetch = require('node-fetch');
const log = require('@lib/utils/log')('Import Blog Filter');

async function importBlog(value, callback) {
let response;
try {
response = await fetch(BLOG_PATH);
} catch (err) {
console.log('Could not fetch blog posts!', err);
log.error('Fetching blog posts failed:', err);
callback(null, []);
return;
}
Expand Down
11 changes: 4 additions & 7 deletions platform/lib/tools/componentReferenceLinker.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

const {Signale} = require('signale');
const log = require('@lib/utils/log')('Component Reference Linker');
const gulp = require('gulp');
const through = require('through2');
const path = require('path');
Expand All @@ -39,16 +39,13 @@ const COMPONENTS_SRC =
*/
class ComponentReferenceLinker {
constructor() {
this._log = new Signale({
'scope': 'Reference linker',
});
this._placeholders = {};
this._codePlaceholders = {};
this._tablePlaceholders = {};
}

async start() {
this._log.start(`Inspecting documents in ${PAGES_SRC} ...`);
log.start(`Inspecting documents in ${PAGES_SRC} ...`);

return new Promise((resolve, reject) => {
let stream = gulp.src(PAGES_SRC, {'read': true, 'base': './'});
Expand All @@ -61,7 +58,7 @@ class ComponentReferenceLinker {

stream.pipe(gulp.dest('./'));
stream.on('end', () => {
this._log.complete('Linked all component references!');
log.complete('Linked all component references!');

resolve();
});
Expand Down Expand Up @@ -135,7 +132,7 @@ class ComponentReferenceLinker {
/* eslint-enable max-len */
for (let i = 0; i < cases.length; i++) {
const results = Array.from(new Set(cases[i]));
console.log({results});
log.info({results});

for (let j = 0; j < results.length; j++) {
const result = results[j];
Expand Down
Loading

0 comments on commit e155fd8

Please sign in to comment.