refactor: move logger to monorepo

This commit is contained in:
2023-03-14 17:15:56 +01:00
parent 1007c280df
commit a9fad2e442
29 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,94 @@
/*
* Copyright (C) 2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {Transport, VerifiableTransport} from './transport';
/**
* A recursive partial object
*
* Copied from https://stackoverflow.com/a/51365037
*/
export type RecursivePartial<T> = {
[P in keyof T]?: T[P] extends Array<infer U>
? Array<RecursivePartial<U>>
: T[P] extends object
? RecursivePartial<T[P]>
: T[P];
};
/**
* Deletes all properties that are undefined from an object
*
* @param object Object to delete undefined properties from
*/
export function deleteUndefinedProperties(object: unknown): unknown {
// return atomic data types and arrays (recursion anchor)
if (typeof object !== 'object' || Array.isArray(object)) {
return object;
}
// check each key
for (const key in object) {
/* istanbul ignore if */
if (!object.hasOwnProperty(key)) {
continue;
}
const indexedObject = object as {[k: string]: unknown};
if (typeof indexedObject[key] === 'undefined') {
// delete undefined keys
delete indexedObject[key];
} else {
// check recursive
indexedObject[key] = deleteUndefinedProperties(indexedObject[key]);
}
}
return object;
}
/**
* Checks if environment is Node.js
*/
export function isNodeEnvironment(): boolean {
return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
}
/**
* Checks if environment is productive
*/
export function isProductiveEnvironment(): boolean {
return (
typeof process.env === 'object' &&
typeof process.env.NODE_ENV !== 'undefined' &&
process.env.NODE_ENV === 'production'
);
}
/**
* Checks if environment is Node.js and productive
*/
export function isProductiveNodeEnvironment(): boolean {
return isNodeEnvironment() && isProductiveEnvironment();
}
/**
* Check if a transport is a verifiable transport
*
* @param transport Transport to check
*/
export function isTransportWithVerification(transport: Transport): transport is VerifiableTransport {
return transport instanceof VerifiableTransport;
}

View File

@@ -0,0 +1,348 @@
/*
* Copyright (C) 2019-2020 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {stringify} from 'flatted';
import {isNodeEnvironment, isProductiveEnvironment, isProductiveNodeEnvironment} from './common';
import {Transformation} from './transformation';
import {AddLogLevel} from './transformations/add-log-level';
import {Transport} from './transport';
/**
* Check if something has property STAPPS_LOG_LEVEL
*
* @param something Something to check
*/
// tslint:disable-next-line:completed-docs
function hasStAppsLogLevel(something: object): something is {STAPPS_LOG_LEVEL: number} {
return 'STAPPS_LOG_LEVEL' in something;
}
/**
* Check if something has property STAPPS_EXIT_LEVEL
*
* @param something Something to check
*/
// tslint:disable-next-line:completed-docs
function hasStAppsExitLevel(something: object): something is {STAPPS_EXIT_LEVEL: number} {
return 'STAPPS_EXIT_LEVEL' in something;
}
/**
* A level descriptor for either log or exit level
*/
export type Level = 'LOG' | 'EXIT';
/**
* A log level
*/
export type LogLevel = 'INFO' | 'LOG' | 'WARN' | 'ERROR' | 'OK';
/**
* A logger with transports and transformations
*
* Log level can be defined by setting the environment variable STAPPS_LOG_LEVEL to a valid log level. Log levels are
* set in a binary way. For example STAPPS_LOG_LEVEL=12 does result in logs only for `Logger.warn` and `Logger.error`.
*
* Log levels in that order are:
* ```
* INFO: 1
* LOG: 2
* WARN: 4
* ERROR: 8
* OK: 16
* ```
*/
export class Logger {
/**
* Base of binary system
*/
private static readonly binaryBase = 2;
/**
* Log levels
*/
private static readonly logLevels: LogLevel[] = ['INFO', 'LOG', 'WARN', 'ERROR', 'OK'];
/**
* Log level sum, equivalent to all log levels enabled
*/
private static readonly logLevelSum = Math.pow(Logger.binaryBase, Logger.logLevels.length) - 1;
/**
* Transformers for log output
*/
private static transformations?: Transformation[] = [new AddLogLevel()];
/**
* Transport for errors
*/
private static transport?: Transport;
/**
* Apply transformations to an output
* Will strip newlines in production environment
*
* @param logLevel Log level of the output
* @param output Output to apply transformations to
*/
private static applyTransformers(logLevel: LogLevel, output: string): string {
if (isProductiveEnvironment()) {
output = output.replace(/[\n\r]/g, ' ');
}
if (!Array.isArray(Logger.transformations) || Logger.transformations.length === 0) {
return output;
}
let transformedOutput = output;
for (const transformation of Logger.transformations) {
transformedOutput = transformation.transform(logLevel, transformedOutput);
}
return transformedOutput;
}
/**
* Check if intended exit level is allowed in environment exit level
*
* @param exitLevel Log level to check
*/
private static checkExitLevel(exitLevel: LogLevel): boolean {
if (Logger.getLevel('EXIT') === 0) {
return false;
}
// tslint:disable-next-line:no-bitwise
return (Logger.getLevel('EXIT') & Logger.logLevelNumber(exitLevel)) === Logger.logLevelNumber(exitLevel);
}
/**
* Check if intended log level is allowed in environment log level
*
* @param logLevel Log level to check
*/
private static checkLogLevel(logLevel: LogLevel): boolean {
// tslint:disable-next-line:no-bitwise
return (Logger.getLevel('LOG') & Logger.logLevelNumber(logLevel)) === Logger.logLevelNumber(logLevel);
}
/**
* Notify about exit and end process
*/
private static exit(): void {
if (isProductiveNodeEnvironment()) {
return;
}
// eslint-disable-next-line no-console
console.error(
Logger.applyTransformers('ERROR', `exiting as of used exit level ${Logger.getLevel('EXIT')} !`),
);
process.exit(-1);
}
/**
* Return log level from environment
*/
private static getLevel(level: Level): number {
if (typeof window !== 'undefined') {
// browser environment exists
if (hasStAppsLogLevel(window)) {
return window.STAPPS_LOG_LEVEL;
}
if (hasStAppsExitLevel(window)) {
return window.STAPPS_EXIT_LEVEL;
}
}
const environmentLevel = level === 'LOG' ? process.env.STAPPS_LOG_LEVEL : process.env.STAPPS_EXIT_LEVEL;
if (isNodeEnvironment() && typeof environmentLevel !== 'undefined') {
// Node.js environment exists
return Number.parseInt(environmentLevel, 10);
}
// Fallback to log everything, or not exiting
switch (level) {
case 'LOG':
return Logger.logLevelSum;
case 'EXIT':
return 0;
}
}
/**
* Get number of specific log level
*
* @param logLevel Log level to check
*/
private static logLevelNumber(logLevel: LogLevel): number {
return Math.pow(Logger.binaryBase, Logger.logLevels.indexOf(logLevel));
}
/**
* Log an error
*
* @param arguments_ Arguments to log
*/
public static async error(...arguments_: unknown[]): Promise<string | void> {
if (!Logger.checkLogLevel('ERROR')) {
return;
}
// eslint-disable-next-line no-console
console.error(Logger.applyTransformers('ERROR', Logger.stringifyArguments(...arguments_)));
if (isProductiveNodeEnvironment()) {
if (typeof Logger.transport !== 'undefined') {
return Logger.transport.send('Error', Logger.stringifyArguments(...arguments_));
}
if (process.env.ALLOW_NO_TRANSPORT !== 'true') {
throw new Error(
`Error couldn't be transported! Please set a transport or set ALLOW_NO_TRANSPORT='true'.`,
);
}
}
if (Logger.checkExitLevel('ERROR')) {
Logger.exit();
}
}
/**
* Log an information
*
* @param arguments_ Arguments to log
*/
public static info(...arguments_: unknown[]): void {
if (!Logger.checkLogLevel('INFO')) {
return;
}
// eslint-disable-next-line no-console
console.info(Logger.applyTransformers('INFO', Logger.stringifyArguments(...arguments_)));
if (Logger.checkExitLevel('INFO')) {
Logger.exit();
}
}
/**
* Check if the logger is initialized correctly
*/
public static initialized(): void {
if (isProductiveNodeEnvironment() && typeof Logger.transport === 'undefined') {
if (process.env.ALLOW_NO_TRANSPORT !== 'true') {
throw new Error(`Productive environment doesn't set a transport for error notifications.`);
}
Logger.warn(`Productive environment doesn't set a transport for error notifications.`);
}
}
/**
* Log something
*
* @param arguments_ Arguments to log
*/
public static log(...arguments_: unknown[]): void {
if (!Logger.checkLogLevel('LOG')) {
return;
}
// eslint-disable-next-line no-console
console.log(Logger.applyTransformers('LOG', Logger.stringifyArguments(...arguments_)));
if (Logger.checkExitLevel('LOG')) {
Logger.exit();
}
}
/**
* Log something successful
*
* @param arguments_ Arguments to log
*/
public static ok(...arguments_: unknown[]): void {
if (!Logger.checkLogLevel('OK')) {
return;
}
// eslint-disable-next-line no-console
console.log(Logger.applyTransformers('OK', Logger.stringifyArguments(...arguments_)));
if (Logger.checkExitLevel('OK')) {
Logger.exit();
}
}
/**
* Set transformations for log output
*
* @param transformations List of transformations
*/
public static setTransformations(transformations: Transformation[]) {
const transforms = transformations.filter(transform =>
isProductiveEnvironment() ? transform.useInProduction === true : true,
);
Logger.transformations = transforms;
}
/**
* Set a transport
*
* @param transport Transport to set
*/
public static setTransport(transport?: Transport) {
Logger.transport = transport;
}
/**
* Stringify a list of arguments
*
* @param arguments_ Arguments to stringify
*/
public static stringifyArguments(...arguments_: unknown[]): string {
const result: string[] = [];
for (const argument of arguments_) {
if (typeof argument === 'string' || typeof argument === 'number') {
result.push(argument.toString());
} else if (argument instanceof Error) {
result.push(argument.message);
if (typeof argument.stack !== 'undefined') {
result.push(argument.stack);
}
} else {
result.push(stringify(argument, undefined, 2));
}
}
return result.join(', ');
}
/**
* Log a warning
*
* @param arguments_ Arguments to log
*/
public static warn(...arguments_: unknown[]): void {
if (!Logger.checkLogLevel('WARN')) {
return;
}
// eslint-disable-next-line no-console
console.warn(Logger.applyTransformers('WARN', Logger.stringifyArguments(...arguments_)));
if (Logger.checkExitLevel('WARN')) {
Logger.exit();
}
}
}

378
packages/logger/src/smtp.ts Normal file
View File

@@ -0,0 +1,378 @@
/*
* Copyright (C) 2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import * as nodemailer from 'nodemailer';
import {MailOptions} from 'nodemailer/lib/sendmail-transport';
import {deleteUndefinedProperties, isProductiveEnvironment, RecursivePartial} from './common';
import {VerifiableTransport} from './transport';
/**
* A configuration of the transport used to send mails via SMTP
*/
export interface SMTPConfig {
/**
* Auth configuration
*/
auth: {
/**
* Password for login
*/
password: string;
/**
* User for login
*/
user: string;
};
/**
* List of "carbon copy" recipients
*/
cc?: string[];
/**
* SMTP host server
*/
host: string;
/**
* SMTP port
*/
port: number;
/**
* List of recipients
*/
recipients: string[];
/**
* Whether or not to establish a secure connection
*/
secure?: boolean;
/**
* Sender configuration
*/
sender: {
/**
* Mail of sender
*/
mail: string;
/**
* Name of sender
*/
name?: string;
};
}
/**
* An implementation of mail transport via SMTP
*/
export class SMTP extends VerifiableTransport {
/**
* Singleton instance
*/
private static _instance: SMTP;
/**
* List of all mail addresses to send in cc
*/
private readonly cc: string[];
/**
* Who is using this service
*/
private readonly from: {
/**
* Mail of sender
*/
mail: string;
/**
* Name of sender
*/
name?: string;
};
/**
* List of all mail addresses to send to
*/
private readonly recipients: string[];
/**
* Connection to SMTP server
*/
private readonly transportAgent: nodemailer.Transporter;
/**
* Set to true if the transport was verified
*/
private verified: boolean;
/**
* Get Singleton Instance of the SMTP Transport
*
* If no config is given it is assumed it will be given via environment variables
* SMTP_AUTH_USER: SMTP username
* SMTP_AUTH_PASSWORD: SMTP password
* SMTP_HOST: SMTP host
* SMTP_PORT: SMTP port
* SMTP_RECIPIENTS: comma seperated list of recipients
* SMTP_CC: comma seperated list of recipients for the carbon copy (CC)
* SMTP_SENDER_MAIL: sender of the mail
* SMTP_SENDER_NAME: name of the sender
* SMTP_SECURE: `true` to enable tls
*
* @param config SMTP config for instance
*/
public static getInstance(config?: SMTPConfig): SMTP | undefined {
// if an instance of SMTP already exists
if (typeof SMTP._instance !== 'undefined') {
return SMTP._instance;
}
// monitoring is not required -> SMTP init can fail
if (!isProductiveEnvironment() || process.env.ALLOW_NO_TRANSPORT === 'true') {
try {
SMTP._instance = new SMTP(config);
} catch {
// eslint-disable-next-line no-console
console.warn('SMTP config failed.');
return;
}
} else {
// monitoring is required -> SMTP will throw error if config is invalid
SMTP._instance = new SMTP(config);
}
return SMTP._instance;
}
/**
* This checks email addresses to be compatible with new standards. RFC 3490 introduced some features that are not
* implemented by every mail transfer agent (MTA).
*
* For more information please consider reading
* https://stackoverflow.com/a/2071250
*
* @param address Address to validate
*/
public static isValidEmailAddress(address: string): boolean {
// tslint:disable-next-line:max-line-length
return /^(([^<>()\[\].,;:\s@"]+(\.[^<>()\[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i.test(
address,
);
}
/**
* Checks a list of mail addresses for validity
*
* @param recipients List of recipients to check
*/
public static isValidRecipientsList(recipients: string[] | undefined): boolean {
return Array.isArray(recipients) && recipients.length > 0 && recipients.every(SMTP.isValidEmailAddress);
}
/**
* Creates an SMTP connection.
*
* WARNING: This class is supposed to be used as a singleton. You should never call `new SMTP()`
*
* @param smtpConfig SMTP config
*/
private constructor(smtpConfig?: SMTPConfig) {
// create a partial config from environment variables that can overwrite the given config
const environmentConfig: RecursivePartial<SMTPConfig> = {
auth: {
password: process.env.SMTP_AUTH_PASSWORD,
user: process.env.SMTP_AUTH_USER,
},
cc: typeof process.env.SMTP_CC !== 'undefined' ? (process.env.SMTP_CC as string).split(',') : [],
host: process.env.SMTP_HOST,
port:
typeof process.env.SMTP_PORT !== 'undefined' ? Number.parseInt(process.env.SMTP_PORT, 10) : undefined,
recipients:
typeof process.env.SMTP_RECIPIENTS !== 'undefined' ? process.env.SMTP_RECIPIENTS.split(',') : [],
secure: typeof process.env.SMTP_SECURE !== 'undefined' ? process.env.SMTP_SECURE === 'true' : false,
sender: {
mail: process.env.SMTP_SENDER_MAIL,
name: process.env.SMTP_SENDER_NAME,
},
};
const config = {
...smtpConfig,
// deleting undefined properties so the actual config doesn't get overwritten by undefined values
...(deleteUndefinedProperties(environmentConfig) as object),
} as SMTPConfig;
if (typeof config.host === 'undefined') {
throw new TypeError(
'SMTP configuration needs a host. Add it to the config or use environment variables (SMTP_HOST).',
);
}
if (typeof config.port === 'undefined' || Number.isNaN(config.port)) {
throw new TypeError(
'SMTP configuration needs a port. Add it to the config or use environment variables (SMTP_PORT).',
);
}
if (typeof config.auth !== 'object') {
throw new TypeError(
'SMTP configuration needs an auth object.' +
'Add it to the config or use environment variables (SMTP_AUTH_USER, SMTP_AUTH_PASSWORD).',
);
}
if (typeof config.auth.user === 'undefined') {
throw new TypeError(
'SMTP auth configuration needs a user. Add it to the config or use environment variables (SMTP_AUTH_USER).',
);
}
if (typeof config.auth.password === 'undefined') {
throw new TypeError(
'SMTP auth configuration needs a password.' +
'Add it to the config or use environment variables (SMTP_AUTH_PASSWORD).',
);
}
if (Array.isArray(config.recipients) && config.recipients.length === 0) {
throw new Error(
'SMTP configuration needs recipients. Add it to the config or use environment variables (SMTP_RECIPIENTS).',
);
}
if (typeof config.sender.mail === 'undefined') {
throw new TypeError(
'SMTP configuration needs a sender. Add it to the config or use environment variables (SMTP_SENDER_MAIL).',
);
}
super();
if (SMTP.isValidRecipientsList(config.recipients)) {
this.recipients = config.recipients;
} else {
throw new Error('Invalid recipients found');
}
if (typeof config.cc !== 'undefined') {
if (SMTP.isValidRecipientsList(config.cc)) {
this.cc = config.cc;
} else {
throw new Error('Invalid cc recipients found');
}
} else {
this.cc = [];
}
this.from = config.sender;
this.verified = false;
// creating transport with configuration
this.transportAgent = nodemailer.createTransport({
auth: {
pass: config.auth.password,
user: config.auth.user,
},
host: config.host,
port: config.port,
secure: typeof config.secure !== 'undefined' ? config.secure : false,
});
}
/**
* Check if instance was verified at least once
*/
public isVerified(): boolean {
return this.verified;
}
/**
* Sends a preconfigured mail with recipients and sender configured on
* creation of the class (set by environment or on creation of this class)
*
* @param subject Subject of the mail
* @param message message of the mail
*/
public async send(subject: string, message: string): Promise<string> {
return this.sendMail({
cc: this.cc,
// use an address block if name is available, mail otherwise
from: typeof this.from.name !== 'string' ? `${this.from.name} <${this.from.mail}>` : this.from.mail,
subject: subject,
text: message,
to: this.recipients,
});
}
/**
* Sends a mail object
*
* @param mail Mail to send
*/
public async sendMail(mail: MailOptions): Promise<string> {
// info is the response of the smtp server
let info = await this.transportAgent.sendMail(mail);
// it can be undefined (empty response)
if (typeof info === 'undefined') {
info = 'Successfully sent mail';
}
// or not of type string
if (typeof info !== 'string') {
info = JSON.stringify(info);
}
return info;
}
/**
* Verify authentication with SMTP server
*
*
* @throws error if you are in a productive environment and don't set ALLOW_NO_TRANSPORT to true
* @returns true if the transport is valid
*/
public async verify(): Promise<boolean> {
let verificationSuccessfull = false;
try {
verificationSuccessfull = await this.transportAgent.verify();
} catch (error) {
if (!isProductiveEnvironment() || process.env.ALLOW_NO_TRANSPORT !== 'true') {
throw error;
}
// eslint-disable-next-line no-console
console.warn(
'SMTP verification error was ignored, because tranport failures are allowed:',
(error as Error).message,
);
}
if (!verificationSuccessfull) {
if (!isProductiveEnvironment() || process.env.ALLOW_NO_TRANSPORT !== 'true') {
throw new Error(
'Verification of SMTP transport failed.' +
'If you want to ignore this error set' +
'`NODE_ENV=dev` or `ALLOW_NO_TRANSPORT=true`',
);
}
// eslint-disable-next-line no-console
console.warn('SMTP verification error was ignored, because tranport failures are allowed.');
}
this.verified = verificationSuccessfull;
return verificationSuccessfull;
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright (C) 2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {LogLevel} from './logger';
/**
* A transformer for log output
*/
export interface Transformation {
/**
* Indicates if this transformation is stripped in production environments
*/
useInProduction: boolean;
/**
* Transform an output
*
* @param logLevel Log level to transform output for
* @param output Output to transform
*/
transform(logLevel: LogLevel, output: string): string;
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright (C) 2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {LogLevel} from '../logger';
import {Transformation} from '../transformation';
/**
* Transformation that adds the log level to output
*/
export class AddLogLevel implements Transformation {
/**
* Keep this transformation in production environments
*/
useInProduction = true;
/**
* Add log level to output
*
* @param logLevel Log level to add to output
* @param output Output to colorize
*/
// tslint:disable-next-line:prefer-function-over-method
transform(logLevel: LogLevel, output: string): string {
return `[${logLevel}] ${output}`;
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright (C) 2019-2020 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import chalk from 'chalk';
import {LogLevel} from '../logger';
import {Transformation} from '../transformation';
/**
* Transformation that colorizes log output
*/
export class Colorize implements Transformation {
/**
* Skip this transformation in production environments
*/
useInProduction = false;
/**
* Instantiate a new colorize transformation
*
* @param logLevelToColor Map from log level to color transformation to apply
*/
constructor(
private readonly logLevelToColor: {[k in LogLevel]: chalk.Chalk} = {
ERROR: chalk.bold.red,
INFO: chalk.cyan,
LOG: chalk.white,
OK: chalk.bold.green,
WARN: chalk.yellow,
},
) {
// noop
}
/**
* Colorize log output
*
* @param logLevel Log level to choose color for
* @param output Output to colorize
*/
transform(logLevel: LogLevel, output: string): string {
return this.logLevelToColor[logLevel](output);
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright (C) 2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {LogLevel} from '../logger';
import {Transformation} from '../transformation';
/**
* Transformation that adds a timestamp to output
*/
export class Timestamp implements Transformation {
/**
* Keep this transformation in production environments
*/
useInProduction = true;
/**
* Add timestamp to output
*
* @param _logLevel Log level to add timestamp to output for
* @param output Output to add timestamp to
*/
transform(_logLevel: LogLevel, output: string): string {
return `[${new Date().toISOString()}] ${output}`;
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright (C) 2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* An abstract wrapper for a transport system like for example SMTP
*/
export abstract class Transport {
/**
* Send message with subject
*
* A message can be a mail or something completely different depending on what transport is implemented.
*
* @param subject Subject of the message
* @param message Message to send
*/
abstract send(subject: string, message: string): Promise<string>;
}
/**
* A transport wrapper of transport which can be verified
*/
export abstract class VerifiableTransport extends Transport {
/**
* Checks if the transport was verified at least once
*/
abstract isVerified(): boolean;
/**
* Verifies transport
*
* Check connection, authentication, ...
*/
abstract verify(): Promise<boolean>;
}