1
0
mirror of https://github.com/journey-ad/Moe-Counter.git synced 2024-12-18 02:15:58 +01:00

feat: Add GA_ID and LOG_LEVEL environment variables

This commit is contained in:
journey-ad 2024-10-31 13:58:21 +08:00
parent f16899d51e
commit 16948c7038
6 changed files with 46 additions and 16 deletions

View File

@ -12,3 +12,9 @@ DB_TYPE=sqlite
# Database write interval in seconds (0 for real-time) # Database write interval in seconds (0 for real-time)
DB_INTERVAL=60 DB_INTERVAL=60
# Log level: either 'debug' | 'info' | 'warn' | 'error' | 'none'
LOG_LEVEL=debug
# Google Analytics `G-Tag` ID
# GA_ID=G-XXXX

1
.gitignore vendored
View File

@ -16,6 +16,7 @@ count.db
# misc # misc
.DS_Store .DS_Store
.env
.env.local .env.local
.env.development.local .env.development.local
.env.test.local .env.test.local

View File

@ -145,8 +145,8 @@
const lazyLoadOptions = { const lazyLoadOptions = {
selector: 'img[data-src]:not([src])', selector: 'img[data-src]:not([src])',
loading: '/img/loading.svg', loading: `${__global_data.site}/img/loading.svg`,
failed: '/img/failed.svg', failed: `${__global_data.site}/img/failed.svg`,
rootMargin: '200px', rootMargin: '200px',
threshold: 0.01 threshold: 0.01
}; };

View File

@ -8,7 +8,7 @@ const { z } = require("zod");
const db = require("./db"); const db = require("./db");
const { themeList, getCountImage } = require("./utils/themify"); const { themeList, getCountImage } = require("./utils/themify");
const { cors, ZodValid } = require("./utils/middleware"); const { cors, ZodValid } = require("./utils/middleware");
const { randomArray } = require("./utils"); const { randomArray, logger } = require("./utils");
const app = express(); const app = express();
@ -19,8 +19,10 @@ app.set("view engine", "pug");
app.get('/', (req, res) => { app.get('/', (req, res) => {
const site = process.env.APP_SITE || `${req.protocol}://${req.get('host')}` const site = process.env.APP_SITE || `${req.protocol}://${req.get('host')}`
const ga_id = process.env.GA_ID || null
res.render('index', { res.render('index', {
site, site,
ga_id,
themeList, themeList,
}) })
}); });
@ -71,7 +73,7 @@ app.get(["/@:name", "/get/@:name"],
res.send(renderSvg); res.send(renderSvg);
console.log( logger.debug(
data, data,
{ theme, ...req.query }, { theme, ...req.query },
`ip: ${req.headers['x-forwarded-for'] || req.connection.remoteAddress}`, `ip: ${req.headers['x-forwarded-for'] || req.connection.remoteAddress}`,
@ -93,11 +95,11 @@ app.get("/record/@:name", async (req, res) => {
app.get("/heart-beat", (req, res) => { app.get("/heart-beat", (req, res) => {
res.set("cache-control", "max-age=0, no-cache, no-store, must-revalidate"); res.set("cache-control", "max-age=0, no-cache, no-store, must-revalidate");
res.send("alive"); res.send("alive");
console.log("heart-beat"); logger.debug("heart-beat");
}); });
const listener = app.listen(process.env.APP_PORT || 3000, () => { const listener = app.listen(process.env.APP_PORT || 3000, () => {
console.log("Your app is listening on port " + listener.address().port); logger.info("Your app is listening on port " + listener.address().port);
}); });
let __cache_counter = {}; let __cache_counter = {};
@ -116,7 +118,7 @@ async function pushDB() {
try { try {
needPush = false; needPush = false;
console.log("pushDB", __cache_counter); logger.info("pushDB", __cache_counter);
const counters = Object.keys(__cache_counter).map((key) => { const counters = Object.keys(__cache_counter).map((key) => {
return { return {
@ -128,7 +130,7 @@ async function pushDB() {
await db.setNumMulti(counters); await db.setNumMulti(counters);
__cache_counter = {}; __cache_counter = {};
} catch (error) { } catch (error) {
console.log("pushDB is error: ", error); logger.error("pushDB is error: ", error);
} }
} }
@ -151,7 +153,7 @@ async function getCountByName(name, num) {
return { name, num: __cache_counter[name] }; return { name, num: __cache_counter[name] };
} catch (error) { } catch (error) {
console.log("get count by name is error: ", error); logger.error("get count by name is error: ", error);
return defaultCount; return defaultCount;
} }
} }

View File

@ -1,8 +1,28 @@
const log_level = process.env.LOG_LEVEL || 'info';
const levels = ['none', 'error', 'warn', 'info', 'debug'];
const currentLevelIndex = levels.indexOf(log_level);
const buildLogMethod = (level) => (...args) => {
const levelIndex = levels.indexOf(level);
const shouldLog = levelIndex <= currentLevelIndex;
if (shouldLog) {
console[level](...args);
}
};
module.exports = { module.exports = {
randomArray: (arr) => { randomArray: (arr) => {
return arr[Math.floor(Math.random() * arr.length)] return arr[Math.floor(Math.random() * arr.length)]
}, },
toFixed: (num, digits = 2) => { toFixed: (num, digits = 2) => {
return parseFloat(Number(num).toFixed(digits)) return parseFloat(Number(num).toFixed(digits))
},
logger: {
debug: buildLogMethod('debug'),
info: buildLogMethod('info'),
warn: buildLogMethod('warn'),
error: buildLogMethod('error')
} }
} }

View File

@ -2,19 +2,20 @@ html
head head
title='Moe Counter!' title='Moe Counter!'
meta(name='viewport', content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no') meta(name='viewport', content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no')
link(rel='icon', type='image/png', href='favicon.png') link(rel='icon', type='image/png', href=`${site}/favicon.png`)
link(rel='stylesheet', href='https://cdn.jsdelivr.net/npm/normalize.css') link(rel='stylesheet', href='https://cdn.jsdelivr.net/npm/normalize.css')
link(rel='stylesheet', href='https://cdn.jsdelivr.net/npm/bamboo.css') link(rel='stylesheet', href='https://cdn.jsdelivr.net/npm/bamboo.css')
link(rel='stylesheet/less', href='style.less') link(rel='stylesheet/less', href=`${site}/style.less`)
script(less, src='https://cdn.jsdelivr.net/npm/less') script(less, src='https://cdn.jsdelivr.net/npm/less')
if ga_id
<!-- Global site tag (gtag.js) - Google Analytics --> <!-- Global site tag (gtag.js) - Google Analytics -->
script(async, src='https://www.googletagmanager.com/gtag/js?id=G-2RLWN5JXRL') script(async, src='https://www.googletagmanager.com/gtag/js?id=#{ga_id}')
script. script.
window.dataLayer = window.dataLayer || []; window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); } function gtag() { dataLayer.push(arguments); }
gtag('js', new Date()); gtag('js', new Date());
gtag('config', 'G-2RLWN5JXRL'); gtag('config', '#{ga_id}');
function _evt_push(type, category, label) { function _evt_push(type, category, label) {
gtag('event', type, { gtag('event', type, {
@ -148,4 +149,4 @@ html
div.back-to-top div.back-to-top
script(async, src='https://cdn.jsdelivr.net/npm/party-js@2/bundle/party.min.js') script(async, src='https://cdn.jsdelivr.net/npm/party-js@2/bundle/party.min.js')
script(async, src='script.js') script(async, src=`${site}/script.js`)