1
1
mirror of https://github.com/kokonect-link/cherrypick synced 2025-01-10 03:43:48 +09:00
cherrypick/packages/backend/src/logger.ts

147 lines
4.8 KiB
TypeScript
Raw Normal View History

/*
2023-08-01 17:16:39 +09:00
* SPDX-FileCopyrightText: syuilo and other misskey, cherrypick contributors
* SPDX-License-Identifier: AGPL-3.0-only
*/
import cluster from 'node:cluster';
2023-06-18 07:48:27 +09:00
import util from 'util';
import chalk from 'chalk';
import { default as convertColor } from 'color-convert';
2022-02-04 10:41:27 +09:00
import { format as dateFormat } from 'date-fns';
2023-06-18 07:48:27 +09:00
import stripAnsi from 'strip-ansi';
import { bindThis } from '@/decorators.js';
2022-09-18 03:27:08 +09:00
import { envOption } from './env.js';
import type { Log } from '@google-cloud/logging';
import type { KEYWORD } from 'color-convert/conversions.js';
2022-12-10 15:45:30 +09:00
type Context = {
name: string;
color?: KEYWORD;
};
type Level = 'error' | 'success' | 'warning' | 'debug' | 'info';
// eslint-disable-next-line import/no-default-export
export default class Logger {
2022-12-10 15:45:30 +09:00
private context: Context;
private parentLogger: Logger | null = null;
private store: boolean;
private cloudLogging: Log | null | undefined;
constructor(context: string, color?: KEYWORD, store = true, cloudLogging?: Log) {
2022-12-10 15:45:30 +09:00
this.context = {
name: context,
color: color,
};
this.store = store;
this.cloudLogging = cloudLogging;
}
@bindThis
public createSubLogger(context: string, color?: KEYWORD, store = true): Logger {
2022-12-10 15:45:30 +09:00
const logger = new Logger(context, color, store);
logger.parentLogger = this;
return logger;
}
@bindThis
2022-12-10 15:45:30 +09:00
private log(level: Level, message: string, data?: Record<string, any> | null, important = false, subContexts: Context[] = [], store = true): void {
if (envOption.quiet) return;
if (!this.store) store = false;
2020-03-28 18:28:21 +09:00
if (level === 'debug') store = false;
if (this.parentLogger) {
2022-12-10 15:45:30 +09:00
this.parentLogger.log(level, message, data, important, [this.context].concat(subContexts), store);
return;
}
2023-06-18 07:48:27 +09:00
const timestamp = new Date();
const time = dateFormat(timestamp, 'HH:mm:ss');
2023-02-09 11:46:08 +09:00
const worker = cluster.isPrimary ? '*' : cluster.worker!.id;
const l =
level === 'error' ? important ? chalk.bgRed.white('ERR ') : chalk.red('ERR ') :
level === 'warning' ? chalk.yellow('WARN') :
level === 'success' ? important ? chalk.bgGreen.white('DONE') : chalk.green('DONE') :
level === 'debug' ? chalk.gray('VERB') :
level === 'info' ? chalk.blue('INFO') :
null;
2022-12-10 15:45:30 +09:00
const contexts = [this.context].concat(subContexts).map(d => d.color ? chalk.rgb(...convertColor.keyword.rgb(d.color))(d.name) : chalk.white(d.name));
const m =
level === 'error' ? chalk.red(message) :
level === 'warning' ? chalk.yellow(message) :
level === 'success' ? chalk.green(message) :
level === 'debug' ? chalk.gray(message) :
level === 'info' ? message :
null;
2022-12-10 15:45:30 +09:00
let log = `${l} ${worker}\t[${contexts.join(' ')}]\t${m}`;
if (envOption.withLogTime) log = chalk.gray(time) + ' ' + log;
console.log(important ? chalk.bold(log) : log);
2023-08-17 16:18:06 +09:00
if (level === 'error' && data) console.log(data);
this.writeCloudLogging(level, log, timestamp, level === 'error' || level === 'warning' ? data : null);
2023-06-18 07:48:27 +09:00
}
private async writeCloudLogging(level: Level, message: string, time: Date, data?: Record<string, any> | null) {
if (!this.cloudLogging) return;
2023-06-18 07:48:27 +09:00
let lv = level;
if (level === 'success') lv = 'info';
const log = this.cloudLogging;
2023-06-18 07:48:27 +09:00
const logMessage = stripAnsi(message);
const metadata = {
severity: lv.toUpperCase(),
resource: {
type: 'global',
timestamp: time,
},
labels: {
name: `${this.context.name}`,
color: `${this.context.color}`,
},
};
const dataString = data ? '\n' + util.inspect(data, { depth: null }) : '';
const entry = log.entry(metadata, logMessage + dataString);
await log.write(entry);
}
@bindThis
public error(x: string | Error, data?: Record<string, any> | null, important = false): void { // 実行を継続できない状況で使う
if (x instanceof Error) {
2022-09-18 03:27:08 +09:00
data = data ?? {};
data.e = x;
this.log('error', x.toString(), data, important);
} else if (typeof x === 'object') {
2022-09-18 03:27:08 +09:00
this.log('error', `${(x as any).message ?? (x as any).name ?? x}`, data, important);
} else {
this.log('error', `${x}`, data, important);
}
}
@bindThis
public warn(message: string, data?: Record<string, any> | null, important = false): void { // 実行を継続できるが改善すべき状況で使う
this.log('warning', message, data, important);
}
@bindThis
public succ(message: string, data?: Record<string, any> | null, important = false): void { // 何かに成功した状況で使う
this.log('success', message, data, important);
}
@bindThis
public debug(message: string, data?: Record<string, any> | null, important = false): void { // デバッグ用に使う(開発者に必要だが利用者に不要な情報)
2022-02-04 10:41:27 +09:00
if (process.env.NODE_ENV !== 'production' || envOption.verbose) {
this.log('debug', message, data, important);
}
}
@bindThis
public info(message: string, data?: Record<string, any> | null, important = false): void { // それ以外
this.log('info', message, data, important);
}
}