Compare commits

...

2 Commits

Author SHA1 Message Date
Fabian Stamm
9182efe7e7 Fixing some problems with the adapter API 2020-04-09 18:00:59 +02:00
Fabian Stamm
94d9731cdd Running everything through prettier 2020-04-09 17:50:30 +02:00
7 changed files with 605 additions and 538 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "@hibas123/logging", "name": "@hibas123/logging",
"version": "2.2.2", "version": "2.3.0",
"description": "", "description": "",
"main": "out/index.js", "main": "out/index.js",
"types": "out/index.d.ts", "types": "out/index.d.ts",

View File

@ -42,6 +42,7 @@ export interface LoggingBaseOptions {
console: boolean; console: boolean;
} }
const adapterCache = new WeakMap<Adapter, number>();
export class LoggingBase { export class LoggingBase {
private _formatMap: FormatConfig = new DefaultFormatConfig(); private _formatMap: FormatConfig = new DefaultFormatConfig();
@ -110,8 +111,12 @@ export class LoggingBase {
addAdapter(adapter: Adapter) { addAdapter(adapter: Adapter) {
if (!this.adapter.has(adapter)) { if (!this.adapter.has(adapter)) {
this.adapter.add(adapter); this.adapter.add(adapter);
let cached = adapterCache.get(adapter) || 0;
adapterCache.set(adapter, cached + 1);
let prms = Promise.resolve( let prms = Promise.resolve(
adapter.init(this.messageObservable.getPublicApi(), this._name) adapter.init(this.messageObservable.getPublicApi())
); );
this.adapter_init.push(prms); this.adapter_init.push(prms);
} }
@ -129,10 +134,29 @@ export class LoggingBase {
} }
} }
private $closed = false;
public close() { public close() {
this.adapter.forEach((adapter) => if (this.$closed) return;
adapter.close ? adapter.close() : undefined this.$closed = true;
);
this.adapter.forEach((adapter) => {
let cached = adapterCache.get(adapter);
if (cached) {
cached--;
if (cached <= 0) {
adapterCache.delete(adapter);
adapter.close();
} else adapterCache.set(adapter, cached);
}
adapter.close ? adapter.close() : undefined;
});
this.adapter = undefined;
this.messageObservable.close();
} }
public waitForSetup() { public waitForSetup() {
@ -234,6 +258,8 @@ export class LoggingBase {
message: any[], message: any[],
caller?: { file: string; line: number } caller?: { file: string; line: number }
) { ) {
if (this.$closed) return;
let date = new Date().toISOString().replace(/T/, " ").replace(/\..+/, ""); let date = new Date().toISOString().replace(/T/, " ").replace(/\..+/, "");
let file_raw = caller || getCallerFile(); let file_raw = caller || getCallerFile();

View File

@ -1,19 +1,11 @@
import { ObservableInterface } from "@hibas123/utils"; import { ObservableInterface } from "@hibas123/utils";
import { Colors } from "./index"; import { Colors } from "./index";
import { import {
<<<<<<< HEAD
Adapter,
Message,
FormattedLine,
TerminalFormats,
FormatTypes
=======
Adapter, Adapter,
Message, Message,
FormattedLine, FormattedLine,
TerminalFormats, TerminalFormats,
FormatTypes, FormatTypes,
>>>>>>> facb7e7b403e1dfaa8790426259e6effb0618efb
} from "./types"; } from "./types";
const browser = typeof window !== "undefined"; const browser = typeof window !== "undefined";
@ -23,11 +15,7 @@ export class ConsoleAdapter implements Adapter {
observable.subscribe(this.onMessage.bind(this)); observable.subscribe(this.onMessage.bind(this));
} }
<<<<<<< HEAD
flush() {} flush() {}
=======
flush() {}
>>>>>>> facb7e7b403e1dfaa8790426259e6effb0618efb
// TODO: Check if required! // TODO: Check if required!
// private escape(text: string): string { // private escape(text: string): string {
@ -148,7 +136,7 @@ export class ConsoleAdapter implements Adapter {
if (browser) { if (browser) {
let formats: string[] = []; let formats: string[] = [];
let text = lines let text = lines
.map(line => { .map((line) => {
let [t, fmts] = this.formatLine(line); let [t, fmts] = this.formatLine(line);
formats.push(...fmts); formats.push(...fmts);
return prefix + t; return prefix + t;
@ -157,7 +145,7 @@ export class ConsoleAdapter implements Adapter {
// console.log(formats); // console.log(formats);
console.log(text, ...formats); console.log(text, ...formats);
} else { } else {
lines.forEach(line => { lines.forEach((line) => {
let [text] = this.formatLine(line); let [text] = this.formatLine(line);
console.log(prefix + text); console.log(prefix + text);
}); });

View File

@ -1,6 +1,11 @@
import { LoggingBase } from "./base"; import { LoggingBase } from "./base";
export { ConsoleAdapter } from "./consolewriter"; export { ConsoleAdapter } from "./consolewriter";
export { LoggingBase, LoggingBaseOptions, removeColors, withColor } from "./base"; export {
LoggingBase,
LoggingBaseOptions,
removeColors,
withColor,
} from "./base";
export { export {
Adapter, Adapter,
LoggingTypes, LoggingTypes,
@ -12,7 +17,7 @@ export {
Colors, Colors,
Format, Format,
FormatTypes, FormatTypes,
TerminalFormats TerminalFormats,
} from "./types"; } from "./types";
export { ObservableInterface } from "@hibas123/utils"; export { ObservableInterface } from "@hibas123/utils";

View File

@ -1,4 +1,3 @@
/** /**
* Module exports. * Module exports.
*/ */
@ -26,7 +25,7 @@ export default function inspect(obj: any, opts: Partial<InspectOptions>) {
depth: undefined, depth: undefined,
colors: undefined, colors: undefined,
showHidden: undefined, showHidden: undefined,
customInspect: undefined customInspect: undefined,
}; };
// legacy... // legacy...
if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 3) ctx.depth = arguments[2];
@ -49,32 +48,32 @@ export default function inspect(obj: any, opts: Partial<InspectOptions>) {
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = { inspect.colors = {
'bold': [1, 22], bold: [1, 22],
'italic': [3, 23], italic: [3, 23],
'underline': [4, 24], underline: [4, 24],
'inverse': [7, 27], inverse: [7, 27],
'white': [37, 39], white: [37, 39],
'grey': [90, 39], grey: [90, 39],
'black': [30, 39], black: [30, 39],
'blue': [34, 39], blue: [34, 39],
'cyan': [36, 39], cyan: [36, 39],
'green': [32, 39], green: [32, 39],
'magenta': [35, 39], magenta: [35, 39],
'red': [31, 39], red: [31, 39],
'yellow': [33, 39] yellow: [33, 39],
}; };
// Don't use 'blue' not visible on cmd.exe // Don't use 'blue' not visible on cmd.exe
inspect.styles = { inspect.styles = {
'special': 'cyan', special: "cyan",
'number': 'yellow', number: "yellow",
'boolean': 'yellow', boolean: "yellow",
'undefined': 'grey', undefined: "grey",
'null': 'bold', null: "bold",
'string': 'green', string: "green",
'date': 'magenta', date: "magenta",
// "name": intentionally not styling // "name": intentionally not styling
'regexp': 'red' regexp: "red",
}; };
function stylizeNoColor(str, styleType) { function stylizeNoColor(str, styleType) {
@ -82,7 +81,7 @@ function stylizeNoColor(str, styleType) {
} }
function isBoolean(arg) { function isBoolean(arg) {
return typeof arg === 'boolean'; return typeof arg === "boolean";
} }
function isUndefined(arg) { function isUndefined(arg) {
@ -93,23 +92,30 @@ function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType]; var style = inspect.styles[styleType];
if (style) { if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str + return (
'\u001b[' + inspect.colors[style][1] + 'm'; "\u001b[" +
inspect.colors[style][0] +
"m" +
str +
"\u001b[" +
inspect.colors[style][1] +
"m"
);
} else { } else {
return str; return str;
} }
} }
function isFunction(arg) { function isFunction(arg) {
return typeof arg === 'function'; return typeof arg === "function";
} }
function isString(arg) { function isString(arg) {
return typeof arg === 'string'; return typeof arg === "string";
} }
function isNumber(arg) { function isNumber(arg) {
return typeof arg === 'number'; return typeof arg === "number";
} }
function isNull(arg) { function isNull(arg) {
@ -121,20 +127,22 @@ function hasOwn(obj, prop) {
} }
function isRegExp(re) { function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]'; return isObject(re) && objectToString(re) === "[object RegExp]";
} }
function isObject(arg) { function isObject(arg) {
return typeof arg === 'object' && arg !== null; return typeof arg === "object" && arg !== null;
} }
function isError(e) { function isError(e) {
return isObject(e) && return (
(objectToString(e) === '[object Error]' || e instanceof Error); isObject(e) &&
(objectToString(e) === "[object Error]" || e instanceof Error)
);
} }
function isDate(d) { function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]'; return isObject(d) && objectToString(d) === "[object Date]";
} }
function objectToString(o) { function objectToString(o) {
@ -155,35 +163,46 @@ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = []; var output = [];
for (var i = 0, l = value.length; i < l; ++i) { for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwn(value, String(i))) { if (hasOwn(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, output.push(
String(i), true)); formatProperty(
ctx,
value,
recurseTimes,
visibleKeys,
String(i),
true
)
);
} else { } else {
output.push(''); output.push("");
} }
} }
keys.forEach(function (key) { keys.forEach(function (key) {
if (!key.match(/^\d+$/)) { if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, output.push(
key, true)); formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)
);
} }
}); });
return output; return output;
} }
function formatError(value) { function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']'; return "[" + Error.prototype.toString.call(value) + "]";
} }
function formatValue(ctx, value, recurseTimes) { function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions. // Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it // Check that value is an object with an inspect function on it
if (ctx.customInspect && if (
ctx.customInspect &&
value && value &&
isFunction(value.inspect) && isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special // Filter out the util module, it's inspect function is special
value.inspect !== inspect && value.inspect !== inspect &&
// Also filter out any prototype objects using the circular check. // Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) { !(value.constructor && value.constructor.prototype === value)
) {
var ret = value.inspect(recurseTimes, ctx); var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) { if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes); ret = formatValue(ctx, ret, recurseTimes);
@ -211,55 +230,59 @@ function formatValue(ctx, value, recurseTimes) {
// IE doesn't make error fields non-enumerable // IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value) if (
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { isError(value) &&
(keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)
) {
return formatError(value); return formatError(value);
} }
// Some type of object without properties can be shortcutted. // Some type of object without properties can be shortcutted.
if (keys.length === 0) { if (keys.length === 0) {
if (isFunction(value)) { if (isFunction(value)) {
var name = value.name ? ': ' + value.name : ''; var name = value.name ? ": " + value.name : "";
return ctx.stylize('[Function' + name + ']', 'special'); return ctx.stylize("[Function" + name + "]", "special");
} }
if (isRegExp(value)) { if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
} }
if (isDate(value)) { if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date'); return ctx.stylize(Date.prototype.toString.call(value), "date");
} }
if (isError(value)) { if (isError(value)) {
return formatError(value); return formatError(value);
} }
} }
var base = '', array = false, braces = ['{', '}']; var base = "",
array = false,
braces = ["{", "}"];
// Make Array say that they are Array // Make Array say that they are Array
if (Array.isArray(value)) { if (Array.isArray(value)) {
array = true; array = true;
braces = ['[', ']']; braces = ["[", "]"];
} }
// Make functions say that they are functions // Make functions say that they are functions
if (isFunction(value)) { if (isFunction(value)) {
var n = value.name ? ': ' + value.name : ''; var n = value.name ? ": " + value.name : "";
base = ' [Function' + n + ']'; base = " [Function" + n + "]";
} }
// Make RegExps say that they are RegExps // Make RegExps say that they are RegExps
if (isRegExp(value)) { if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value); base = " " + RegExp.prototype.toString.call(value);
} }
// Make dates with properties first say the date // Make dates with properties first say the date
if (isDate(value)) { if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value); base = " " + Date.prototype.toUTCString.call(value);
} }
// Make error with message first say the error // Make error with message first say the error
if (isError(value)) { if (isError(value)) {
base = ' ' + formatError(value); base = " " + formatError(value);
} }
if (keys.length === 0 && (!array || value.length == 0)) { if (keys.length === 0 && (!array || value.length == 0)) {
@ -268,9 +291,9 @@ function formatValue(ctx, value, recurseTimes) {
if (recurseTimes < 0) { if (recurseTimes < 0) {
if (isRegExp(value)) { if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
} else { } else {
return ctx.stylize('[Object]', 'special'); return ctx.stylize("[Object]", "special");
} }
} }
@ -281,7 +304,14 @@ function formatValue(ctx, value, recurseTimes) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else { } else {
output = keys.map(function (key) { output = keys.map(function (key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); return formatProperty(
ctx,
value,
recurseTimes,
visibleKeys,
key,
array
);
}); });
} }
@ -311,17 +341,17 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
} }
if (desc.get) { if (desc.get) {
if (desc.set) { if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special'); str = ctx.stylize("[Getter/Setter]", "special");
} else { } else {
str = ctx.stylize('[Getter]', 'special'); str = ctx.stylize("[Getter]", "special");
} }
} else { } else {
if (desc.set) { if (desc.set) {
str = ctx.stylize('[Setter]', 'special'); str = ctx.stylize("[Setter]", "special");
} }
} }
if (!hasOwn(visibleKeys, key)) { if (!hasOwn(visibleKeys, key)) {
name = '[' + key + ']'; name = "[" + key + "]";
} }
if (!str) { if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) { if (ctx.seen.indexOf(desc.value) < 0) {
@ -330,76 +360,88 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
} else { } else {
str = formatValue(ctx, desc.value, recurseTimes - 1); str = formatValue(ctx, desc.value, recurseTimes - 1);
} }
if (str.indexOf('\n') > -1) { if (str.indexOf("\n") > -1) {
if (array) { if (array) {
str = str.split('\n').map(function (line) { str = str
return ' ' + line; .split("\n")
}).join('\n').substr(2); .map(function (line) {
return " " + line;
})
.join("\n")
.substr(2);
} else { } else {
str = '\n' + str.split('\n').map(function (line) { str =
return ' ' + line; "\n" +
}).join('\n'); str
.split("\n")
.map(function (line) {
return " " + line;
})
.join("\n");
} }
} }
} else { } else {
str = ctx.stylize('[Circular]', 'special'); str = ctx.stylize("[Circular]", "special");
} }
} }
if (isUndefined(name)) { if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) { if (array && key.match(/^\d+$/)) {
return str; return str;
} }
name = JSON.stringify('' + key); name = JSON.stringify("" + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2); name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name'); name = ctx.stylize(name, "name");
} else { } else {
name = name.replace(/'/g, "\\'") name = name
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') .replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'"); .replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string'); name = ctx.stylize(name, "string");
} }
} }
return name + ': ' + str; return name + ": " + str;
} }
function formatPrimitive(ctx, value) { function formatPrimitive(ctx, value) {
if (isUndefined(value)) if (isUndefined(value)) return ctx.stylize("undefined", "undefined");
return ctx.stylize('undefined', 'undefined');
if (isString(value)) { if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') var simple =
"'" +
JSON.stringify(value)
.replace(/^"|"$/g, "")
.replace(/'/g, "\\'") .replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\''; .replace(/\\"/g, '"') +
return ctx.stylize(simple, 'string'); "'";
return ctx.stylize(simple, "string");
} }
if (isNumber(value)) if (isNumber(value)) return ctx.stylize("" + value, "number");
return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize("" + value, "boolean");
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here. // For some reason typeof null is "object", so special case here.
if (isNull(value)) if (isNull(value)) return ctx.stylize("null", "null");
return ctx.stylize('null', 'null');
} }
function reduceToSingleString(output, base, braces) { function reduceToSingleString(output, base, braces) {
var numLinesEst = 0; var numLinesEst = 0;
var length = output.reduce(function (prev, cur) { var length = output.reduce(function (prev, cur) {
numLinesEst++; numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++; if (cur.indexOf("\n") >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; return prev + cur.replace(/\u001b\[\d\d?m/g, "").length + 1;
}, 0); }, 0);
if (length > 60) { if (length > 60) {
return braces[0] + return (
(base === '' ? '' : base + '\n ') + braces[0] +
' ' + (base === "" ? "" : base + "\n ") +
output.join(',\n ') + " " +
' ' + output.join(",\n ") +
braces[1]; " " +
braces[1]
);
} }
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; return braces[0] + base + " " + output.join(", ") + " " + braces[1];
} }
function _extend<T extends Y, Y>(origin: T, add: Y) { function _extend<T extends Y, Y>(origin: T, add: Y) {

View File

@ -4,10 +4,9 @@ export enum LoggingTypes {
Debug, Debug,
Log, Log,
Warning, Warning,
Error Error,
} }
export const TerminalFormats = { export const TerminalFormats = {
Reset: "\x1b[0m", Reset: "\x1b[0m",
Bold: "\x1b[1m", Bold: "\x1b[1m",
@ -32,15 +31,14 @@ export const TerminalFormats = {
BgBlue: "\x1b[44m", BgBlue: "\x1b[44m",
BgMagenta: "\x1b[45m", BgMagenta: "\x1b[45m",
BgCyan: "\x1b[46m", BgCyan: "\x1b[46m",
BgWhite: "\x1b[47m" BgWhite: "\x1b[47m",
} };
export enum FormatTypes { export enum FormatTypes {
COLOR, COLOR,
BOLD, BOLD,
UNDERSCORE, UNDERSCORE,
BLINK BLINK,
} }
export enum Colors { export enum Colors {
@ -51,7 +49,7 @@ export enum Colors {
BLUE, BLUE,
MAGENTA, MAGENTA,
CYAN, CYAN,
WHITE WHITE,
} }
export interface FormatConfig { export interface FormatConfig {
@ -67,12 +65,12 @@ export interface FormatConfig {
function colorFormat(color: Colors) { function colorFormat(color: Colors) {
return { return {
type: FormatTypes.COLOR, type: FormatTypes.COLOR,
color color,
} };
} }
const boldFormat = { const boldFormat = {
type: FormatTypes.BOLD type: FormatTypes.BOLD,
}; };
export class DefaultFormatConfig implements FormatConfig { export class DefaultFormatConfig implements FormatConfig {
@ -101,19 +99,27 @@ export interface Message {
type: LoggingTypes; type: LoggingTypes;
name?: string; name?: string;
text: { text: {
raw: string[], raw: string[];
formatted: FormattedLine[] formatted: FormattedLine[];
}; };
date: Date; date: Date;
file: string; file: string;
} }
export interface Adapter { export interface Adapter {
init(observable: ObservableInterface<Message>, name?: string): void | Promise<void>; /**
* This function initialises the Adapter. It might be called multiple times, when added to multiple instances
* @param observable An observable to subscribe to messages
*/
init(observable: ObservableInterface<Message>): void | Promise<void>;
flush(sync: true): void; flush(sync: true): void;
flush(sync: false): void | Promise<void>; flush(sync: false): void | Promise<void>;
/**
* When a close function is available, it will be called when no logging instance references it anymore.
*
* WARNING: The adapter might be reinitialised, when it is added to a new Logging instance
*/
close?(): void; close?(): void;
} }