Skip to content
Merged
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"strip-ansi": "^7.2.0",
"typescript": "^7.0.2"
},
"packageManager": "pnpm@11.13.0",
"packageManager": "pnpm@11.11.0",
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
Expand Down
16 changes: 4 additions & 12 deletions src/createLogger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import { LOG_LEVEL, LOG_TYPES } from './constants.js';
import { isErrorStackMessage, stripAnsi } from './utils.js';
import type { Options, LogMessage, Logger, LogMethods } from './types.js';

const LABEL_WIDTH = 7;

const normalizeErrorMessage = (err: Error) => {
if (err.stack) {
const [rawName, ...rest] = err.stack.split('\n');
Expand Down Expand Up @@ -38,8 +36,8 @@ export const createLogger = (options: Options = {}) => {
}

const label = 'label' in logType ? logType.label : '';
const header = label ? (prefix ? `${label} ${prefix}` : label) : prefix;
let text = '';
const hasLabel = Boolean(label);

const isErrorObject = message instanceof Error;

Expand All @@ -63,14 +61,8 @@ export const createLogger = (options: Options = {}) => {
text = `${message}`;
}

if (prefix) {
text = `${prefix} ${text}`;
}

if (alignMultiline && hasLabel && !isErrorObject && text.includes('\n')) {
const indent = ' '.repeat(
LABEL_WIDTH + 1 + (prefix ? stripAnsi(prefix).length + 1 : 0),
);
if (alignMultiline && header && !isErrorObject && text.includes('\n')) {
const indent = ' '.repeat(stripAnsi(header).length + 1);
const skipStack = level === 'error';
text = text
.split('\n')
Expand All @@ -83,7 +75,7 @@ export const createLogger = (options: Options = {}) => {
}

const method = level === 'error' || level === 'warn' ? level : 'log';
console[method](label ? `${label} ${text}` : text, ...args);
console[method](header ? `${header} ${text}` : text, ...args);
};

const logger = {
Expand Down
16 changes: 16 additions & 0 deletions tests/logger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,22 @@ describe('logger', () => {
).toMatchSnapshot();
});

test('should align multi-line log messages to prefix column', () => {
console.log = rs.fn();

const alignLogger = createLogger({
alignMultiline: true,
prefix: '[web]',
});

alignLogger.log(`First line
Second line`);

expect(stripAnsi((console.log as Mock).mock.calls[0][0].toString()))
.toBe(`[web] First line
Second line`);
});
Comment thread
chenjiahan marked this conversation as resolved.

test('should keep error stacks top-aligned when alignMultiline is enabled', () => {
console.error = rs.fn();

Expand Down