Skip to content

Commit

Permalink
feat: pass formatOptions and other options to reporters
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Apr 10, 2023
1 parent c4fff18 commit d77286a
Show file tree
Hide file tree
Showing 13 changed files with 118 additions and 115 deletions.
2 changes: 1 addition & 1 deletion examples/fancy.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FancyReporter } from "../src/reporters";
import { reporterDemo } from "./utils";

reporterDemo(new FancyReporter({}));
reporterDemo(new FancyReporter());
2 changes: 1 addition & 1 deletion examples/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,5 @@ export function reporterDemo(reporter) {
}

export const consola = createConsola({
reporters: [new FancyReporter({})],
reporters: [new FancyReporter()],
});
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"@vitest/coverage-c8": "^0.29.8",
"changelogen": "^0.5.2",
"colorette": "^2.0.19",
"defu": "^6.1.2",
"eslint": "^8.37.0",
"eslint-config-unjs": "^0.1.0",
"figures": "^5.0.0",
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

54 changes: 26 additions & 28 deletions src/consola.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,17 @@
import { defu } from "defu";
import { LogTypes, LogType, LogLevel } from "./constants";
import { isLogObj } from "./utils/index";
import type { ConsolaReporter, InputLogObject, LogObject } from "./types";
import type {
ConsolaReporter,
InputLogObject,
LogObject,
ConsolaOptions,
} from "./types";
import type { PromptOptions } from "./prompt";

let paused = false;
const queue: any[] = [];

export interface ConsolaOptions {
reporters: ConsolaReporter[];
types: Record<LogType, InputLogObject>;
level: LogLevel;
defaults: InputLogObject;
throttle: number;
throttleMin: number;
stdout?: NodeJS.WritableStream;
stderr?: NodeJS.WritableStream;
mockFn?: (type: LogType, defaults: InputLogObject) => (...args: any) => void;
prompt?: typeof import("./prompt").prompt | undefined;
}

export class Consola {
options: ConsolaOptions;

Expand All @@ -33,18 +26,24 @@ export class Consola {
constructor(options: Partial<ConsolaOptions> = {}) {
// Options
const types = options.types || LogTypes;
this.options = {
// Defaults
throttle: 1000,
throttleMin: 5,
// User
...options,
// Overrides, Normalizations and Clones
defaults: { ...options.defaults },
level: _normalizeLogLevel(options.level, types),
reporters: [...(options.reporters || [])],
types,
};
this.options = defu(
<ConsolaOptions>{
...options,
defaults: { ...options.defaults },
level: _normalizeLogLevel(options.level, types),
reporters: [...(options.reporters || [])],
},
<ConsolaOptions>{
types: LogTypes,
throttle: 1000,
throttleMin: 5,
formatOptions: {
date: true,
colors: false,
compact: true,
},
}
);

// Create logger functions for current instance
for (const type in types) {
Expand Down Expand Up @@ -353,8 +352,7 @@ export class Consola {
_log(logObj: LogObject) {
for (const reporter of this.options.reporters) {
reporter.log(logObj, {
stdout: this.stdout,
stderr: this.stderr,
options: this.options,
});
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/index.browser.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import BrowserReporter from "./reporters/browser";
import { createConsola as _createConsola } from "./consola";
import type { ConsolaOptions } from "./consola";
import type { ConsolaOptions } from "./types";

export * from "./index.shared";

Expand Down
12 changes: 8 additions & 4 deletions src/index.node.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { isDebug, isTest, isCI } from "std-env";
import { LogLevels, LogLevel } from "./constants";
import type { ConsolaOptions } from "./consola";
import type { ConsolaOptions } from "./types";
import { BasicReporter, FancyReporter } from "./reporters";
import { createConsola as _createConsola } from "./consola";
import { ConsolaInstance, createConsola as _createConsola } from "./consola";

export * from "./index.shared";

export function createConsola(options: Partial<ConsolaOptions> = {}) {
export function createConsola(
options: Partial<ConsolaOptions> = {}
): ConsolaInstance {
// Log level
let level = _getDefaultLogLevel();
if (process.env.CONSOLA_LEVEL) {
Expand All @@ -17,9 +19,11 @@ export function createConsola(options: Partial<ConsolaOptions> = {}) {
const consola = _createConsola({
level: level as LogLevel,
defaults: { level },
stdout: process.stdout,
stderr: process.stderr,
prompt: (...args) => import("./prompt").then((m) => m.prompt(...args)),
reporters: options.reporters || [
isCI || isTest ? new BasicReporter({}) : new FancyReporter({}),
isCI || isTest ? new BasicReporter() : new FancyReporter(),
],
...options,
});
Expand Down
6 changes: 3 additions & 3 deletions src/index.shared.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export { Consola } from "./consola";
export { LogLevels, LogTypes } from "./constants";
export { Consola } from "./consola";

export type { ConsolaInstance, ConsolaOptions } from "./consola";
export type { LogLevel, LogType } from "./constants";
export type * from "./types";
export type { ConsolaInstance } from "./consola";
export type { LogLevel, LogType } from "./constants";
55 changes: 25 additions & 30 deletions src/reporters/basic.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,43 @@
import util from "node:util";
import { LogObject } from "../types";
import { formatWithOptions } from "node:util";
import type {
LogObject,
ConsolaReporter,
ConsolaOptions,
FormatOptions,
} from "../types";
import { parseStack } from "../utils/error";
import { writeStream } from "../utils/stream";

const DEFAULTS = {
formatOptions: {
date: true,
colors: false,
compact: true,
},
};

const bracket = (x: string) => (x ? `[${x}]` : "");

export default class BasicReporter {
options: typeof DEFAULTS;

constructor(options: Partial<typeof DEFAULTS>) {
this.options = { ...DEFAULTS, ...options };
}

formatStack(stack: string) {
export default class BasicReporter implements ConsolaReporter {
formatStack(stack: string, opts: FormatOptions) {
return " " + parseStack(stack).join("\n ");
}

formatArgs(args: any[]) {
formatArgs(args: any[], opts: FormatOptions) {
const _args = args.map((arg) => {
if (arg && typeof arg.stack === "string") {
return arg.message + "\n" + this.formatStack(arg.stack);
return arg.message + "\n" + this.formatStack(arg.stack, opts);
}
return arg;
});

// Only supported with Node >= 10
// https://nodejs.org/api/util.html#util_util_inspect_object_options
return typeof util.formatWithOptions === "function"
? util.formatWithOptions(this.options.formatOptions, ..._args)
: util.format(..._args);
return formatWithOptions(opts, ..._args);
}

formatDate(date: Date) {
return this.options.formatOptions.date ? date.toLocaleTimeString() : "";
formatDate(date: Date, opts: FormatOptions) {
return opts.date ? date.toLocaleTimeString() : "";
}

filterAndJoin(arr: any[]) {
return arr.filter(Boolean).join(" ");
}

formatLogObj(logObj: LogObject, _opts: any) {
const message = this.formatArgs(logObj.args);
formatLogObj(logObj: LogObject, opts: FormatOptions) {
const message = this.formatArgs(logObj.args, opts);

return this.filterAndJoin([
bracket(logObj.type),
Expand All @@ -57,11 +46,17 @@ export default class BasicReporter {
]);
}

log(logObj: LogObject, { stdout, stderr }: any = {}) {
log(logObj: LogObject, ctx: { options: ConsolaOptions }) {
const line = this.formatLogObj(logObj, {
width: stdout.columns || 0,
columns: (ctx.options.stdout as any).columns || 0,
...ctx.options.formatOptions,
});

return writeStream(line + "\n", logObj.level < 2 ? stderr : stdout);
return writeStream(
line + "\n",
logObj.level < 2
? ctx.options.stderr || process.stderr
: ctx.options.stdout || process.stdout
);
}
}
27 changes: 13 additions & 14 deletions src/reporters/fancy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { mainSymbols } from "figures";
import * as colors from "colorette";
import { parseStack } from "../utils/error";
import { TYPE_COLOR_MAP, LEVEL_COLOR_MAP } from "../utils/fancy";
import { LogObject } from "../types";
import { FormatOptions, LogObject } from "../types";
import BasicReporter from "./basic";

const DEFAULTS = {
Expand All @@ -24,10 +24,6 @@ const TYPE_ICONS = {
};

export default class FancyReporter extends BasicReporter {
constructor(options: Partial<typeof DEFAULTS>) {
super({ ...DEFAULTS, ...options });
}

formatStack(stack: string) {
return (
"\n" +
Expand All @@ -43,11 +39,11 @@ export default class FancyReporter extends BasicReporter {
);
}

formatType(logObj: LogObject, isBadge: boolean) {
formatType(logObj: LogObject, isBadge: boolean, opts: FormatOptions) {
const typeColor =
(TYPE_COLOR_MAP as any)[logObj.type] ||
(LEVEL_COLOR_MAP as any)[logObj.level] ||
(this.options as any).secondaryColor;
"gray";

if (isBadge) {
return getBgColor(typeColor)(
Expand All @@ -62,20 +58,22 @@ export default class FancyReporter extends BasicReporter {
return _type ? getColor(typeColor)(_type) : "";
}

formatLogObj(logObj: LogObject, opts: { width: number }) {
const [message, ...additional] = this.formatArgs(logObj.args).split("\n");
formatLogObj(logObj: LogObject, opts: FormatOptions) {
const [message, ...additional] = this.formatArgs(logObj.args, opts).split(
"\n"
);

const isBadge =
typeof (logObj as any).badge !== "undefined"
? Boolean((logObj as any).badge)
: logObj.level < 2;

const secondaryColor = getColor((this.options as any).secondaryColor);
const secondaryColor = getColor("gray");

const date = this.formatDate(logObj.date);
const date = this.formatDate(logObj.date, opts);
const coloredDate = date && secondaryColor(date);

const type = this.formatType(logObj, isBadge);
const type = this.formatType(logObj, isBadge, opts);

const tag = logObj.tag ? secondaryColor(logObj.tag) : "";

Expand All @@ -86,10 +84,11 @@ export default class FancyReporter extends BasicReporter {
let line;
const left = this.filterAndJoin([type, formattedMessage]);
const right = this.filterAndJoin([tag, coloredDate]);
const space = opts.width - stringWidth(left) - stringWidth(right) - 2;
const space =
(opts.columns || 0) - stringWidth(left) - stringWidth(right) - 2;

line =
space > 0 && opts.width >= 80
space > 0 && (opts.columns || 0) >= 80
? left + " ".repeat(space) + right
: `[ ${right} ] ${left}`;

Expand Down
31 changes: 22 additions & 9 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@
import { InspectOptions } from "node:util";
import type { LogLevel, LogType } from "./constants";

export interface ConsolaOptions {
reporters: ConsolaReporter[];
types: Record<LogType, InputLogObject>;
level: LogLevel;
defaults: InputLogObject;
throttle: number;
throttleMin: number;
stdout?: NodeJS.WriteStream;
stderr?: NodeJS.WriteStream;
mockFn?: (type: LogType, defaults: InputLogObject) => (...args: any) => void;
prompt?: typeof import("./prompt").prompt | undefined;
formatOptions: FormatOptions;
}

export interface FormatOptions {
columns?: number;
date?: boolean;
colors?: boolean;
compact?: boolean;
}

export interface InputLogObject {
level?: LogLevel;
tag?: string;
Expand All @@ -23,14 +43,7 @@ export interface ConsolaReporter {
log: (
logObj: LogObject,
ctx: {
stdout: NodeJS.WritableStream;
stderr: NodeJS.WritableStream;
options: ConsolaOptions;
}
) => void;
}

export interface BasicReporterOptions {
dateFormat?: string;
formatOptions?: InspectOptions;
secondaryColor?: string;
}
Loading

0 comments on commit d77286a

Please sign in to comment.