feat: add logger

This commit is contained in:
Anselm Stordeur
2018-11-28 18:23:15 +01:00
commit 911d71cf3b
16 changed files with 5329 additions and 0 deletions

351
src/Logger.ts Normal file
View File

@@ -0,0 +1,351 @@
/*
* Copyright (C) 2018 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 'circular-json';
import { Transport, TransportWithVerification } from './Transport';
/**
* Logger with colors, loglevel and transport
*
* 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:
* ```
* 1 - INFO
* 2 - LOG
* 4 - WARN
* 8 - ERROR
* 16 - OK
* ```
*/
export class Logger {
/*
* Reset = "\x1b[0m"
* Bright = "\x1b[1m"
* Dim = "\x1b[2m"
* Underscore = "\x1b[4m"
* Blink = "\x1b[5m"
* Reverse = "\x1b[7m"
* Hidden = "\x1b[8m"
*
* FgBlack = "\x1b[30m"
* FgRed = "\x1b[31m"
* FgGreen = "\x1b[32m"
* FgYellow = "\x1b[33m"
* FgBlue = "\x1b[34m"
* FgMagenta = "\x1b[35m"
* FgCyan = "\x1b[36m"
* FgWhite = "\x1b[37m"
*
* BgBlack = "\x1b[40m"
* BgRed = "\x1b[41m"
* BgGreen = "\x1b[42m"
* BgYellow = "\x1b[43m"
* BgBlue = "\x1b[44m"
* BgMagenta = "\x1b[45m"
* BgCyan = "\x1b[46m"
* BgWhite = "\x1b[47m"
*/
/**
* Prefix for cyan color
*/
private cyan = '\x1b[36m';
/**
* Prefix for green color
*/
private green = '\x1b[32m';
/**
* Set to true if this code is executed by Node.js
*/
private isNode: boolean;
/**
* Set to true if the environment for a productive environment is given
*
* In Node.js this means that `NODE_ENV` is set to `production`
*/
private isProductiveEnvironment: boolean;
/**
* Log levels
*/
private logLevels: { [logLevel: string]: 1 | 2 | 4 | 8 | 16 } = {
'INFO': 1,
'LOG': 2,
'WARN': 4,
// tslint:disable-next-line:object-literal-sort-keys
'ERROR': 8,
'OK': 16,
};
/**
* Prefix for red color
*/
private red = '\x1b[31m';
/**
* Suffix to end a color
*/
private reset = '\x1b[0m';
/**
* Transport for errors
*
* For example `@stapps/smtp-transport`
*/
private transport?: Transport;
/**
* Prefix for white color
*/
private white = '\x1b[37m';
/**
* Prefix for yellow color
*/
private yellow = '\x1b[33m';
/**
* Checks if this code is executed in Node.js
*/
public static isNodeEnvironment(): boolean {
// Only Node.js has a process variable that is of [[Class]] process
return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
}
/**
* Checks if a productive environment is given
*/
public static isProductiveEnvironment(): boolean {
return Logger.isNodeEnvironment &&
(typeof process.env.NODE_ENV === 'string' && process.env.NODE_ENV === 'production');
}
/**
* Instatiate an instance of logger
* @param transport A transport instance that can be used for error transport
*/
constructor(transport?: Transport) {
// node environment -> maybe we run a service which needs monitoring
if (Logger.isNodeEnvironment()) {
this.isNode = true;
// check if we are in productive environment -> then we need to run a transport
if (Logger.isProductiveEnvironment()) {
this.isProductiveEnvironment = true;
if (typeof transport === 'undefined') {
if (process.env.ALLOW_NO_TRANSPORT !== 'true') {
throw new Error('Productive environment doesn\'t set an transport agent for error notifications');
} else {
this.warn('Productive environment doesn\'t set an transport agent for error notifications');
}
} else {
this.transport = transport;
// we expect an transport for error notifications
if (this.isTransportWithVerification(transport) && !transport.isVerified()) {
transport.verify().then((success) => {
if (typeof success === 'string') {
this.ok(success);
} else {
this.ok('Successfully verified transport for error notification');
}
}).catch((err) => {
throw err;
});
}
}
} else {
this.isProductiveEnvironment = false;
}
} else {
this.isProductiveEnvironment = false;
this.isNode = false;
}
}
/**
* Check if intended log level is allowed in environment log level
*
* @param logLevel
* @returns {boolean}
*/
private checkLogLevel(logLevel: 1 | 2 | 4 | 8 | 16) {
const requiredLogLevel = this.getLogLevel();
if (requiredLogLevel > 31 || requiredLogLevel < 0) {
throw new Error('Log level is out of range.');
}
// tslint:disable-next-line:no-bitwise
return requiredLogLevel & logLevel;
}
/**
* Return log level from environment
* @returns {number}
*/
private getLogLevel(): number {
if (this.isNode && typeof process.env.STAPPS_LOG_LEVEL === 'string') {
// Node.js environment exists
return parseInt(process.env.STAPPS_LOG_LEVEL, 10);
} else if (typeof window !== 'undefined' && typeof (window as any).STAPPS_LOG_LEVEL === 'number') {
// browser environment exists
return (window as any).STAPPS_LOG_LEVEL;
}
// Log everything
return 31;
}
private isTransportWithVerification(transport: Transport): transport is TransportWithVerification {
return typeof (transport as any).verify === 'function';
}
/**
* Stringify a list of arguments
*
* @param args {any[]} Arguments to stringify
* @returns {string} Stringified arguments
*/
private stringifyArguments(..._args: any[]): string {
const result: string[] = [];
/* tslint:disable:prefer-for-of */
for (let idx = 0; idx < arguments.length; idx++) {
/* tslint:enable */
const argument = arguments[idx];
const type = typeof argument;
if (['string', 'number'].indexOf(type) !== -1) {
result.push(argument);
} else if (argument instanceof Error) {
result.push(argument.message);
if (typeof argument.stack !== 'undefined') {
result.push(argument.stack);
}
} else {
result.push(stringify(argument, null, 2));
}
}
return result.join(', ');
}
/**
* Log with level ERROR
*
* @param args {any} Arguments to log
*/
public error(...args: any[]): void {
if (this.checkLogLevel(this.logLevels.ERROR)) {
if (this.isNode) {
/* tslint:disable-next-line:no-console */
console.error(this.red + '[ERROR] ' + this.stringifyArguments(...args) + this.reset);
if (this.isProductiveEnvironment) {
if (typeof this.transport === 'undefined') {
if (process.env.ALLOW_NO_TRANSPORT !== 'true') {
throw new Error('Error couldn\'t be tranported. Please set an transport or set ALLOW_NO_TRANSPORT=true');
}
} else {
this.transport.send('Error', this.stringifyArguments(...args)).catch((err) => {
throw err;
});
}
}
} else {
/* tslint:disable-next-line:no-console */
console.log('[ERROR] ' + this.stringifyArguments(...args));
}
}
}
/**
* Log with level INFO
*
* @param args {any} Arguments to log
*/
public info(...args: any[]): void {
if (this.checkLogLevel(this.logLevels.INFO)) {
if (this.isNode) {
/* tslint:disable-next-line:no-console */
console.info(this.cyan + '[INFO] ' + this.stringifyArguments(...args) + this.reset);
} else {
/* tslint:disable-next-line:no-console */
console.info('[INFO] ' + this.stringifyArguments(...args));
}
}
}
/**
* Log with level LOG
*
* @param args {any} Arguments to log
*/
public log(...args: any[]): void {
if (this.checkLogLevel(this.logLevels.LOG)) {
if (this.isNode) {
/* tslint:disable-next-line:no-console */
console.log(this.white + '[LOG] ' + this.stringifyArguments(...args) + this.reset);
} else {
/* tslint:disable-next-line:no-console */
console.log('[LOG] ' + this.stringifyArguments(...args));
}
}
}
/**
* Log with level OK
*
* @param args {any} Arguments to log
*/
public ok(...args: any[]): void {
if (this.checkLogLevel(this.logLevels.OK)) {
if (this.isNode) {
/* tslint:disable-next-line:no-console */
console.log(this.green + '[OK] ' + this.stringifyArguments(...args) + this.reset);
} else {
/* tslint:disable-next-line:no-console */
console.log('[OK] ' + this.stringifyArguments(...args));
}
}
}
/**
* Log with level WARN
*
* @param args {any} Arguments to log
*/
public warn(...args: any[]): void {
if (this.checkLogLevel(this.logLevels.WARN)) {
if (this.isNode) {
/* tslint:disable-next-line:no-console */
console.warn(this.yellow + '[WARN] ' + this.stringifyArguments(...args) + this.reset);
} else {
/* tslint:disable-next-line:no-console */
console.warn('[WARN] ' + this.stringifyArguments(...args));
}
}
}
}

346
src/SMTP.ts Normal file
View File

@@ -0,0 +1,346 @@
/*
* Copyright (C) 2018 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 { Logger } from './Logger';
import { TransportWithVerification } from './Transport';
/**
* A configuration of the transport used to send mails via SMTP
*/
export interface SMTPConfig {
auth: {
password: string;
user: string;
};
cc?: string[];
host: string;
port: number;
recipients: string[];
secure?: boolean;
sender: {
mail: string;
name?: string;
};
}
/**
* An implementation of mail transport via SMTP
*/
export class SMTP extends TransportWithVerification {
private static _instance: SMTP;
/**
* List of all mail addresses to send in cc
*/
private cc: string[];
/**
* Who is using this service
*/
private from: {
mail: string;
name?: string;
};
/**
* List of all mail addresses to send to
*/
private recipients: string[];
/**
* Connection to SMTP server
*/
private 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 {SMTPConfig}
* @return {Transport}
*/
public static getInstance(config?: SMTPConfig): SMTP | undefined {
// if an instance of SMTP already exists
if (this._instance) {
return this._instance;
}
// if no config is given, we assume it is set via environment variables
if (typeof config === 'undefined') {
if (typeof process.env.SMTP_AUTH_USER !== 'string') {
throw new Error('User of SMTP configuration is empty. Please provide a user.');
}
if (typeof process.env.SMTP_AUTH_PASSWORD !== 'string') {
throw new Error('Password of SMTP configuration is empty. Please provide a password.');
}
if (typeof process.env.SMTP_HOST !== 'string') {
throw new Error('Host of SMTP configuration is empty. Please provide a host.');
}
if (typeof process.env.SMTP_PORT !== 'string') {
throw new Error('Port of SMTP configuration is empty. Please provide a port.');
}
if (typeof process.env.SMTP_RECIPIENTS !== 'string') {
throw new Error('Recipients of SMTP configuration is empty. Please provide at least one recipient.');
}
if (typeof process.env.SMTP_SENDER_MAIL !== 'string') {
throw new Error('Sender of SMTP configuration is empty. Please provide a sender.');
}
if (typeof process.env.SMTP_SENDER_NAME !== 'string') {
throw new Error('Name of sender of SMTP configuration is empty. Please provide a name for the sender.');
}
config = {
auth: {
password: process.env.SMTP_AUTH_PASSWORD,
user: process.env.SMTP_AUTH_USER,
},
cc: ((typeof process.env.SMTP_CC === 'string') ? (process.env.SMTP_CC as string).split(',') : []),
host: process.env.SMTP_HOST,
port: parseInt(process.env.SMTP_PORT, 10),
recipients: (typeof process.env.SMTP_RECIPIENTS === 'string') ?
(process.env.SMTP_RECIPIENTS).split(',') :
[],
secure: (typeof process.env.SMTP_SECURE === 'string') ? (process.env.SMTP_SECURE === 'true') : false,
sender: {
mail: process.env.SMTP_SENDER_MAIL,
name: process.env.SMTP_SENDER_NAME,
},
};
}
// monitoring is not required -> SMTP init can fail
if (!Logger.isProductiveEnvironment() || process.env.ALLOW_NO_TRANSPORT === 'true') {
try {
this._instance = new this(config);
} catch (err) {
/* tslint:disable-next-line:no-console */
console.warn('SMTP config failed.');
return;
}
} else {
// monitoring is required -> SMTP will throw error if config is invalid
this._instance = new this(config);
}
return this._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 {string} address
* @return {boolean}
*/
public static isValidEmailAddress(address: string): boolean {
if (typeof address !== 'string') {
return false;
}
// tslint:disable-next-line:max-line-length
const regex = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
return regex.test(address);
}
/**
* Checks a list of mail addresses for validity.
* @param {string[]} recipients
* @return {string[]}
*/
public static isValidRecipientsList(recipients: string[]): boolean {
return Array.isArray(recipients) && recipients.length > 0 && recipients.every(this.isValidEmailAddress);
}
/**
* Creates an SMTP connection. WARNING: This class is supposed to be used as a singleton. You should never
* call `new SMTP()`
* @param {SMTPConfig} config
*/
private constructor(config: SMTPConfig) {
if (typeof config.host !== 'string') {
throw new Error('SMTP configuration needs a host.');
}
if (typeof config.port !== 'number') {
throw new Error('SMTP configuration needs a port.');
}
if (typeof config.auth !== 'object') {
throw new Error('SMTP configuration needs an auth object.');
}
if (typeof config.auth.user !== 'string') {
throw new Error('SMTP auth configuration needs a user');
}
if (typeof config.auth.password !== 'string') {
throw new Error('SMTP auth configuration needs a password');
}
if (Array.isArray(config.recipients) && config.recipients.length < 1) {
throw new Error('SMTP configuration needs recipients.');
}
if (typeof config.sender.mail !== 'string') {
throw new Error('SMTP configuration needs a sender');
}
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) || (Array.isArray(config.cc) && config.cc.length === 0)) {
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 === 'boolean' ? config.secure : false,
});
}
/**
* Check if instance was verified at least once
* @returns {boolean}
*/
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 {string} subject
* @param {string} message
*/
public async send(subject: string, message: string): Promise<string> {
return await 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 {MailOptions} mail
*/
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: boolean = false;
try {
verificationSuccessfull = await this.transportAgent.verify();
} catch (err) {
if (!Logger.isProductiveEnvironment() || process.env.ALLOW_NO_TRANSPORT !== 'true') {
throw err;
} else {
/* tslint:disable-next-line:no-console */
console.warn(
'SMTP verification error was ignored, because tranport failures are allowed: ',
err.message,
);
}
}
if (!verificationSuccessfull) {
if (!Logger.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`',
);
} else {
/* tslint:disable-next-line:no-console */
console.warn('SMTP verification error was ignored, because tranport failures are allowed.');
}
}
this.verified = verificationSuccessfull;
return verificationSuccessfull;
}
}

47
src/Transport.ts Normal file
View File

@@ -0,0 +1,47 @@
/*
* Copyright (C) 2018 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 completly different. Depending on what Transport
* is implemented
* @param {string} subject
* @param {string} message
*/
abstract send(subject: string, message: string): Promise<string>;
}
/**
* A transport wrapper of transport which can be veriefied
*/
export abstract class TransportWithVerification extends Transport {
/**
* Checks if the transport was verified at least once
* @returns {boolean}
*/
abstract isVerified(): boolean;
/**
* Verifies transport (check connection, authentication, ...)
*/
abstract verify(): Promise<boolean>;
}