feat: add configurable logging level for backend and Mini App

- Introduced a new `LOG_LEVEL` configuration option in the `.env.example` file to allow users to set the logging level (DEBUG, INFO, WARNING, ERROR).
- Updated the `Settings` class to include the `log_level` attribute, normalizing its value to ensure valid logging levels are used.
- Modified the logging setup in `run.py` to utilize the configured log level, enhancing flexibility in log management.
- Enhanced the Mini App to include the logging level in the JavaScript configuration, allowing for consistent logging behavior across the application.
- Added a new `logger.js` module for frontend logging, implementing level-based filtering and console delegation.
- Included unit tests for the new logger functionality to ensure proper behavior and level handling.
This commit is contained in:
2026-03-02 23:15:22 +03:00
parent 67ba9826c7
commit 43386b15fa
16 changed files with 226 additions and 15 deletions

View File

@@ -6,6 +6,7 @@ import { FETCH_TIMEOUT_MS } from "./constants.js";
import { getInitData } from "./auth.js";
import { state } from "./dom.js";
import { t } from "./i18n.js";
import { logger } from "./logger.js";
/**
* Build fetch options with init data header, Accept-Language and timeout abort.
@@ -49,10 +50,17 @@ export async function apiGet(path, params = {}, options = {}) {
const query = new URLSearchParams(params).toString();
const url = query ? `${base}${path}?${query}` : `${base}${path}`;
const initData = getInitData();
logger.debug("API request", path, params);
const opts = buildFetchOptions(initData, options.signal);
try {
const res = await fetch(url, { headers: opts.headers, signal: opts.signal });
if (!res.ok) {
logger.warn("API non-OK response", path, res.status);
}
return res;
} catch (e) {
logger.error("API request failed", path, e);
throw e;
} finally {
opts.cleanup();
}
@@ -69,6 +77,7 @@ export async function apiGet(path, params = {}, options = {}) {
export async function fetchDuties(from, to, signal) {
const res = await apiGet("/api/duties", { from, to }, { signal });
if (res.status === 403) {
logger.warn("Access denied", from, to);
let detail = t(state.lang, "access_denied");
try {
const body = await res.json();

View File

@@ -2,6 +2,8 @@
* Telegram init data and access checks.
*/
import { logger } from "./logger.js";
/**
* Get tgWebAppData value from hash when it contains unencoded & and =.
* Value runs from tgWebAppData= until next &tgWebApp or end.
@@ -33,7 +35,10 @@ export function getInitData() {
const hash = window.location.hash ? window.location.hash.slice(1) : "";
if (hash) {
const fromHash = getTgWebAppDataFromHash(hash);
if (fromHash) return fromHash;
if (fromHash) {
logger.debug("initData from hash");
return fromHash;
}
const hashParams = new URLSearchParams(hash);
const tgFromHash = hashParams.get("tgWebAppData");
if (tgFromHash) return tgFromHash;
@@ -42,6 +47,7 @@ export function getInitData() {
? new URLSearchParams(window.location.search).get("tgWebAppData")
: null;
if (q) {
logger.debug("initData from query");
return q;
}
return "";

View File

@@ -110,7 +110,7 @@ export const MESSAGES = {
"contact.back": "Назад",
"contact.phone": "Телефон",
"contact.telegram": "Telegram",
"current_duty.title": "Текущее дежурство",
"current_duty.title": "Сейчас дежурит",
"current_duty.no_duty": "Сейчас никто не дежурит",
"current_duty.shift": "Смена",
"current_duty.remaining": "Осталось: {hours}ч {minutes}мин",

71
webapp/js/logger.js Normal file
View File

@@ -0,0 +1,71 @@
/**
* Frontend logger with configurable level (window.__DT_LOG_LEVEL).
* Only messages at or above the configured level are forwarded to console.
* Prefix [DutyTeller][level] for DevTools filtering.
*/
const LEVEL_ORDER = { debug: 0, info: 1, warn: 2, error: 3 };
/**
* Resolve current log level from window.__DT_LOG_LEVEL. Default: info.
* @returns {string} One of "debug", "info", "warn", "error"
*/
function getLogLevel() {
const raw =
(typeof window !== "undefined" && window.__DT_LOG_LEVEL) || "info";
const level = String(raw).toLowerCase();
return LEVEL_ORDER.hasOwnProperty(level) ? level : "info";
}
/**
* Return true if message at level should be emitted (level >= configured).
* @param {string} messageLevel - "debug" | "info" | "warn" | "error"
* @returns {boolean}
*/
function shouldLog(messageLevel) {
const configured = getLogLevel();
const configuredNum = LEVEL_ORDER[configured] ?? 1;
const messageNum = LEVEL_ORDER[messageLevel] ?? 1;
return messageNum >= configuredNum;
}
const PREFIX = "[DutyTeller]";
function logAt(level, args) {
if (!shouldLog(level)) return;
const consoleMethod =
level === "debug"
? console.debug
: level === "info"
? console.info
: level === "warn"
? console.warn
: console.error;
const prefix = `${PREFIX}[${level}]`;
if (args.length === 0) {
consoleMethod(prefix);
} else if (args.length === 1) {
consoleMethod(prefix, args[0]);
} else {
consoleMethod(prefix, ...args);
}
}
/**
* Logger object with debug, info, warn, error (signature like console).
* Example: logger.info("Loaded", { count: 5 });
*/
export const logger = {
debug(msg, ...args) {
logAt("debug", [msg, ...args]);
},
info(msg, ...args) {
logAt("info", [msg, ...args]);
},
warn(msg, ...args) {
logAt("warn", [msg, ...args]);
},
error(msg, ...args) {
logAt("error", [msg, ...args]);
},
};

94
webapp/js/logger.test.js Normal file
View File

@@ -0,0 +1,94 @@
/**
* Unit tests for logger: level filtering and console delegation.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { logger } from "./logger.js";
describe("logger", () => {
const origWindow = globalThis.window;
beforeEach(() => {
vi.spyOn(console, "debug").mockImplementation(() => {});
vi.spyOn(console, "info").mockImplementation(() => {});
vi.spyOn(console, "warn").mockImplementation(() => {});
vi.spyOn(console, "error").mockImplementation(() => {});
});
afterEach(() => {
vi.restoreAllMocks();
if (globalThis.window) {
delete globalThis.window.__DT_LOG_LEVEL;
}
});
function setLevel(level) {
if (!globalThis.window) globalThis.window = {};
globalThis.window.__DT_LOG_LEVEL = level;
}
it("at level info does not call console.debug", () => {
setLevel("info");
logger.debug("test");
expect(console.debug).not.toHaveBeenCalled();
});
it("at level info calls console.info for logger.info", () => {
setLevel("info");
logger.info("hello");
expect(console.info).toHaveBeenCalledWith("[DutyTeller][info]", "hello");
});
it("at level info calls console.warn and console.error", () => {
setLevel("info");
logger.warn("w");
logger.error("e");
expect(console.warn).toHaveBeenCalledWith("[DutyTeller][warn]", "w");
expect(console.error).toHaveBeenCalledWith("[DutyTeller][error]", "e");
});
it("at level debug calls console.debug", () => {
setLevel("debug");
logger.debug("dbg");
expect(console.debug).toHaveBeenCalledWith("[DutyTeller][debug]", "dbg");
});
it("at level error does not call console.debug or console.info", () => {
setLevel("error");
logger.debug("d");
logger.info("i");
expect(console.debug).not.toHaveBeenCalled();
expect(console.info).not.toHaveBeenCalled();
});
it("at level error calls console.error", () => {
setLevel("error");
logger.error("err");
expect(console.error).toHaveBeenCalledWith("[DutyTeller][error]", "err");
});
it("passes extra args to console", () => {
setLevel("info");
logger.info("msg", { foo: 1 }, "bar");
expect(console.info).toHaveBeenCalledWith(
"[DutyTeller][info]",
"msg",
{ foo: 1 },
"bar"
);
});
it("defaults to info when __DT_LOG_LEVEL is missing", () => {
if (globalThis.window) delete globalThis.window.__DT_LOG_LEVEL;
logger.debug("no");
expect(console.debug).not.toHaveBeenCalled();
logger.info("yes");
expect(console.info).toHaveBeenCalledWith("[DutyTeller][info]", "yes");
});
it("defaults to info when __DT_LOG_LEVEL is invalid", () => {
setLevel("invalid");
logger.debug("no");
expect(console.debug).not.toHaveBeenCalled();
});
});

View File

@@ -17,6 +17,7 @@ import {
} from "./dom.js";
import { showAccessDenied, hideAccessDenied, showError, setNavEnabled } from "./ui.js";
import { fetchDuties, fetchCalendarEvents } from "./api.js";
import { logger } from "./logger.js";
import {
dutiesByDate,
calendarEventsByDate,
@@ -65,6 +66,8 @@ export function applyLangToUi() {
applyLangToUi();
logger.info("App init", "lang=" + state.lang);
window.__dtReady = true;
/**
@@ -148,6 +151,7 @@ async function loadMonth() {
const from = localDateString(start);
const to = localDateString(gridEnd);
try {
logger.debug("Loading month", from, to);
const dutiesPromise = fetchDuties(from, to, signal);
const eventsPromise = fetchCalendarEvents(from, to, signal);
const duties = await dutiesPromise;
@@ -186,6 +190,7 @@ async function loadMonth() {
return;
}
if (e.message === "ACCESS_DENIED") {
logger.warn("Access denied in loadMonth", e.serverDetail);
showAccessDenied(e.serverDetail);
setNavEnabled(true);
if (
@@ -198,6 +203,7 @@ async function loadMonth() {
}
return;
}
logger.error("Load month failed", e);
showError(e.message || t(state.lang, "error_generic"), loadMonth);
setNavEnabled(true);
return;