From a60291bec293a48f8112f6a434007a00dcf30ba7 Mon Sep 17 00:00:00 2001 From: Manuel Date: Wed, 5 May 2021 08:13:31 +0200 Subject: [PATCH] Add loglevel, public setting and config env * Log levels for less spam when running in production * Add 'public' setting that allows to not post the invite link for the /help command * config env variable that allows running multiple instances with different config --- config.default.json | 4 ++- index.js | 59 ++++++++++++++++++++++++--------------------- package.json | 1 + 3 files changed, 35 insertions(+), 29 deletions(-) diff --git a/config.default.json b/config.default.json index 948b395..082aa3b 100644 --- a/config.default.json +++ b/config.default.json @@ -1,10 +1,12 @@ { + "loglevel": "info", "http": { "port": 3002 }, "discord": { "token": "", - "client_id": "" + "client_id": "", + "public": true }, "templates": { "bee": { diff --git a/index.js b/index.js index a160aa9..f630a16 100644 --- a/index.js +++ b/index.js @@ -11,10 +11,13 @@ const config = require('./config.default.json'); const filters = require('./filters.js'); +const logger = require('loglevel'); +logger.setLevel(config.loglevel || 'info'); + try { - _.extend(config, require('./config')); // eslint-disable-line global-require + _.extend(config, require(`./${process.env.CONFIG || 'config'}`)); // eslint-disable-line global-require } catch (err) { - console.log('No config.json found!'); + logger.error('No config.json found!'); } function all(x, c) { @@ -61,9 +64,9 @@ function render(template, img, size, flipH) { if (!size.height) imgHeight = imgHeight * size.width / img.width; } - console.log('Drawing template: ', template); + logger.debug('Drawing template: ', template); const anchor = getNumericAnchor(template.anchor, imgWidth, imgHeight); - console.log('Numeric anchor: ', anchor); + logger.debug('Numeric anchor: ', anchor); const xScale = imgWidth / anchor.x.size; const yScale = imgHeight / anchor.y.size; const templateScale = Math.max(0, Math.min(10, Math.max(xScale || 0, yScale || 0))); @@ -73,10 +76,10 @@ function render(template, img, size, flipH) { templateOffsetX = calculatePosition(templateScale, anchor.x, imgWidth); templateOffsetY = calculatePosition(templateScale, anchor.y, imgHeight); - console.log('xScale', xScale); - console.log('yScale', yScale); - console.log('templateOffsetX', templateOffsetX); - console.log('templateOffsetY', templateOffsetY); + logger.debug('xScale', xScale); + logger.debug('yScale', yScale); + logger.debug('templateOffsetX', templateOffsetX); + logger.debug('templateOffsetY', templateOffsetY); let imageOffsetX = 0; let imageOffsetY = 0; @@ -129,13 +132,13 @@ function render(template, img, size, flipH) { attributes: template.attributes, filter: filters[template.filter] }].sort((u, v) => u.z - v.z); - console.log('To draw:', toDraw); + logger.debug('To draw:', toDraw); let canvas = new CanvasEx(resultingWidth, resultingHeight); for (let i = 0; i < toDraw.length; ++i) { const subject = toDraw[i]; - console.log(`Drawing ${subject.name}${subject.flipH ? ' (flipped)' : ''}`); + logger.debug(`Drawing ${subject.name}${subject.flipH ? ' (flipped)' : ''}`); try { const transform = {}; if (subject.flipH) { @@ -152,7 +155,7 @@ function render(template, img, size, flipH) { }); } } catch (err) { - console.error(err); + logger.error(err); throw new Error(JSON.stringify({ status: 400, error: 'Invalid template' })); } } @@ -165,10 +168,10 @@ app.get('/debug/frame/', async (req, res) => { try { const img = new ImageEx(req.query.url); await img.loaded; - console.log(img.frames); + logger.debug(img.frames); return img.frames[req.query.num].canvas.pngStream().pipe(res); } catch (err) { - console.log(err); + logger.error(err); return res.status(400).end(err.message); } }); @@ -181,11 +184,11 @@ app.get('/', async (req, res) => { templateList.push(key); } } - console.log(templateList); + logger.debug(templateList); res.setHeader('Content-Type', 'application/json') return res.end(JSON.stringify(templateList)); } catch (err) { - console.log(err); + logger.error(err); return res.status(400).end(err.message); } }); @@ -197,7 +200,7 @@ app.get('/:templateName/', async (req, res) => { return res.status(400).end('Invalid url!'); } let direction = req.query.reverse === 'true' ? '\\' : '/'; - console.log('Got command ', direction, req.params.templateName, direction === '\\' ? 'flipped' : 'not flipped', req.query.url); + logger.debug('Got command ', direction, req.params.templateName, direction === '\\' ? 'flipped' : 'not flipped', req.query.url); result = new ImageEx(req.query.url); await result.loaded; // eslint-disable-line no-await-in-loop const templateData = templates[req.params.templateName]; @@ -207,13 +210,13 @@ app.get('/:templateName/', async (req, res) => { return result.export(res); } catch (err) { - console.log(err); + logger.error(err); return res.status(400).end({'error': err.message}); } }); app.listen(config.http.port, () => { - console.log(`Beebot app listening on port ${config.http.port}!`); + logger.info(`Beebot app listening on port ${config.http.port}!`); }); @@ -228,11 +231,11 @@ const invitelink = `https://discordapp.com/oauth2/authorize?client_id=${ config.discord.client_id}&scope=bot&permissions=0`; /* const authlink = `https://discordapp.com/oauth2/authorize?client_id=${ config.discord.client_id}&scope=email`; */ -console.log(`Bot invite link: ${invitelink}`); +logger.info(`Bot invite link: ${invitelink}`); client.login(config.discord.token).catch(error => { if (error) { - console.error("Couldn't login: ", error.toString()); + logger.error("Couldn't login: ", error.toString()); } }); @@ -294,8 +297,8 @@ function reverseString(str) { const commands = Object.keys(templates).map(x => `/${x}`).join(', '); const otherCommands = { invite: `Invite link: <${invitelink}>`, - help: `Available commands: ${commands}.\nUse \\\\ to flip the template horizontally.\nInvite link: <${invitelink}>`, - beebot: `Available commands: ${commands}.\nUse \\\\ to flip the template horizontally.\nInvite link: <${invitelink}>` + help: `Available commands: ${commands}.\nUse \\\\ to flip the template horizontally.${config.discord.public ? "\nInvite link: <" + invitelink + ">" : ""}`, + beebot: `Available commands: ${commands}.\nUse \\\\ to flip the template horizontally.${config.discord.public ? "\nInvite link: <" + invitelink + ">" : ""}` }; @@ -323,7 +326,7 @@ client.on('message', async message => { if (commandParsed) { const [, direction, command] = commandParsed; if (templates[command]) { - console.log('Got command ', direction, command, direction === '\\' ? 'flipped' : 'not flipped', emoji); + logger.debug('Got command ', direction, command, direction === '\\' ? 'flipped' : 'not flipped', emoji); count++; name += command; if (result === null) { @@ -344,20 +347,20 @@ client.on('message', async message => { { attachment, name: `${name}.${emoji.ext}` } ] }; - console.log('Sending message with result:', result); + logger.debug('Sending message with result:', result); await message.channel.send('', messageOptions).then(() => { - console.log('Message sent!'); + logger.debug('Message sent!'); }).catch(err => { - console.error('Message sending failed:', err); + logger.error('Message sending failed:', err); }); } } } catch (err) { - console.error(err); + logger.error(err); } } }); process.on('uncaughtException', exception => { - console.log(exception); + logger.error(exception); }); diff --git a/package.json b/package.json index 1f36d13..e146bb4 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "gifencoder": "^1.1.0", "got": "^8.0.1", "lodash": "^4.17.13", + "loglevel": "^1.7.1", "mime-types": "^2.1.17", "omggif": "^1.0.9", "request": "^2.88.0",