From d07e7b834831230b53860d0919a68edc2d36193d Mon Sep 17 00:00:00 2001 From: Kristóf Marussy Date: Sat, 8 Jan 2022 21:36:43 +0100 Subject: build: Eslint fixes for multi-module project MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Kristóf Marussy --- packages/main/src/utils/log.ts | 66 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 packages/main/src/utils/log.ts (limited to 'packages/main/src/utils/log.ts') diff --git a/packages/main/src/utils/log.ts b/packages/main/src/utils/log.ts new file mode 100644 index 0000000..c704797 --- /dev/null +++ b/packages/main/src/utils/log.ts @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2021-2022 Kristóf Marussy + * + * This file is part of Sophie. + * + * Sophie is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import chalk, { ChalkInstance } from 'chalk'; +import loglevel, { Logger } from 'loglevel'; +import prefix from 'loglevel-plugin-prefix'; + +if (import.meta.env?.DEV) { + loglevel.setLevel('debug'); +} else { + loglevel.setLevel('info'); +} + +const COLORS: Partial> = { + TRACE: chalk.magenta, + DEBUG: chalk.cyan, + INFO: chalk.blue, + WARN: chalk.yellow, + ERROR: chalk.red, + CRITICAL: chalk.red, +}; + +function getColor(level: string): ChalkInstance { + return COLORS[level] ?? chalk.gray; +} + +prefix.reg(loglevel); +prefix.apply(loglevel, { + format(level, name, timestamp) { + const levelColor = getColor(level); + const timeStr = timestamp.toString(); + const nameStr = typeof name === 'undefined' + ? levelColor(':') + : ` ${chalk.green(`${name}:`)}`; + return `${chalk.gray(`[${timeStr}]`)} ${levelColor(level)}${nameStr}`; + }, +}); + +export function getLogger(loggerName: string): Logger { + return loglevel.getLogger(loggerName); +} + +export function silenceLogger(): void { + loglevel.disableAll(); + const loggers = loglevel.getLoggers(); + Object.keys(loggers).forEach((loggerName) => { + loggers[loggerName].disableAll(); + }); +} -- cgit v1.2.3-54-g00ecf