Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,29 @@ Following settings are available for styling:
- **Time zone support:**
- `prettyLogTimeZone`: Set timezone of pretty log messages to either `UTC` (default) or `local` (based on your server/browser configuration)

#### prettyLogLevelMethod

Map log levels to specific console methods.

This lets you route each log level to a different output method (e.g., `console.warn`, `console.error`).

```javascript
const logger = new Logger({
type: "pretty",
prettyLogLevelMethod: {
TRACE: console.trace,
DEBUG: console.debug,
INFO: console.info,
WARN: console.warn,
ERROR: console.error,
FATAL: console.error,
"*": console.log
}
});
````

If a level is not specified, `*` is used. If that is not set, then it falls back to `console.log`

#### Log meta information
`tslog` collects meta information for every log, like runtime, code position etc. The meta information collected depends on the runtime (browser or Node.js) and is accessible through the `LogObj`.
You can define the property containing this meta information with `metaProperty`, which is "_meta" by default.
Expand Down
21 changes: 18 additions & 3 deletions src/BaseLogger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ export function createLoggerEnvironment(): LoggerEnvironment {
const logErrorsStr = (logErrors.length > 0 && logArgs.length > 0 ? "\n" : "") + logErrors.join("\n");
const sanitizedMetaMarkup = stripAnsi(logMetaMarkup);
const metaMarkupForText = prettyLogs ? logMetaMarkup : sanitizedMetaMarkup;
const log = getPrettyLogMethod(logMeta?.logLevelName, settings.prettyLogLevelMethod)

if (shouldUseCss(prettyLogs)) {
settings.prettyInspectOptions.colors = false;
Expand All @@ -115,16 +116,16 @@ export function createLoggerEnvironment(): LoggerEnvironment {
const output = metaOutput + formattedArgs + logErrorsStr;

if (hasCssMeta) {
console.log(output, ...cssMeta.styles);
log(output, ...cssMeta.styles);
} else {
console.log(output);
log(output);
}
return;
}

settings.prettyInspectOptions.colors = prettyLogs;
const formattedArgs = formatWithOptionsSafe(settings.prettyInspectOptions, logArgs);
console.log(metaMarkupForText + formattedArgs + logErrorsStr);
log(metaMarkupForText + formattedArgs + logErrorsStr);
},
transportJSON<LogObj>(json: LogObj & ILogObjMeta): void {
console.log(jsonStringifyRecursive(json));
Expand Down Expand Up @@ -269,6 +270,19 @@ export function createLoggerEnvironment(): LoggerEnvironment {
return value.replace(ANSI_REGEX, "");
}

function getPrettyLogMethod(
logLevelName: string | undefined,
prettyLogLevelMethod: Record<string, (...args: unknown[]) => void> | undefined
): (...args: unknown[]) => void {
if (logLevelName && prettyLogLevelMethod?.[logLevelName]) {
return prettyLogLevelMethod[logLevelName];
}
if (prettyLogLevelMethod?.["*"]) {
return prettyLogLevelMethod["*"];
}
return console.log;
}

function buildCssMetaOutput<LogObj>(settings: ISettings<LogObj>, metaValue: IMeta | undefined): { text: string; styles: string[] } {
if (metaValue == null) {
return { text: "", styles: [] };
Expand Down Expand Up @@ -770,6 +784,7 @@ export class BaseLogger<LogObj> {
fileName: ["yellow"],
fileNameWithLine: "white",
},
prettyLogLevelMethod: settings?.prettyLogLevelMethod ?? {},
prettyInspectOptions: settings?.prettyInspectOptions ?? {
colors: true,
compact: false,
Expand Down
2 changes: 2 additions & 0 deletions src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export interface ISettingsParam<LogObj> {
stylePrettyLogs?: boolean;
prettyLogTimeZone?: "UTC" | "local";
prettyLogStyles?: IPrettyLogStyles;
prettyLogLevelMethod?: {[logLevelName: string]: (...args: unknown[]) => void}
prettyInspectOptions?: InspectOptions;
metaProperty?: string;
maskPlaceholder?: string;
Expand Down Expand Up @@ -103,6 +104,7 @@ export interface ISettings<LogObj> extends ISettingsParam<LogObj> {
errorName?: TStyle;
errorMessage?: TStyle;
};
prettyLogLevelMethod: {[logLevelName: string]: (...args: unknown[]) => void}
prettyInspectOptions: InspectOptions;
metaProperty: string;
maskPlaceholder: string;
Expand Down
48 changes: 48 additions & 0 deletions tests/7_pretty_Settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,3 +417,51 @@ describe("Pretty: Settings", () => {
expect(getConsoleLogStripped()).toContain(`LOG4`);
});
});

test("prettyLogLevelMethod: dispatches to correct console method per level", (): void => {
const traceSpy = jest.fn();
const debugSpy = jest.fn();
const infoSpy = jest.fn();
const warnSpy = jest.fn();
const errorSpy = jest.fn();
const fallbackSpy = jest.fn();

const logger = new Logger({
type: "pretty",
prettyLogLevelMethod: {
TRACE: traceSpy,
DEBUG: debugSpy,
INFO: infoSpy,
WARN: warnSpy,
ERROR: errorSpy,
FATAL: errorSpy,
"*": fallbackSpy,
},
});

logger.trace("trace message")
expect(traceSpy).toHaveBeenCalledWith(expect.stringContaining("trace message"));
expect(traceSpy).toHaveBeenCalledTimes(1);

logger.debug("debug message")
expect(debugSpy).toHaveBeenCalledWith(expect.stringContaining("debug message"));
expect(debugSpy).toHaveBeenCalledTimes(1);

logger.info("info message");
expect(infoSpy).toHaveBeenCalledWith(expect.stringContaining("info message"));
expect(infoSpy).toHaveBeenCalledTimes(1);

logger.warn("warn message");
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("warn message"));
expect(warnSpy).toHaveBeenCalledTimes(1);

logger.error("error message");
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("error message"));
logger.fatal("fatal message");
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("fatal message"));
expect(errorSpy).toHaveBeenCalledTimes(2);

logger.silly("silly message");
expect(fallbackSpy).toHaveBeenCalledWith(expect.stringContaining("silly message"));
expect(fallbackSpy).toHaveBeenCalledTimes(1);
});