Skip to content

Commit

Permalink
perf: optimize logger (#15574)
Browse files Browse the repository at this point in the history
  • Loading branch information
patak-dev committed Jan 11, 2024
1 parent d0d5938 commit 0fb9071
Showing 1 changed file with 35 additions and 21 deletions.
56 changes: 35 additions & 21 deletions packages/vite/src/node/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,18 @@ export interface LoggerOptions {
customLogger?: Logger
}

// Only initialize the timeFormatter when the timestamp option is used, and
// reuse it across all loggers
let timeFormatter: Intl.DateTimeFormat
function getTimeFormatter() {
timeFormatter ??= new Intl.DateTimeFormat(undefined, {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
})
return timeFormatter
}

export function createLogger(
level: LogLevel = 'info',
options: LoggerOptions = {},
Expand All @@ -59,53 +71,55 @@ export function createLogger(
return options.customLogger
}

const timeFormatter = new Intl.DateTimeFormat(undefined, {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
})
const loggedErrors = new WeakSet<Error | RollupError>()
const { prefix = '[vite]', allowClearScreen = true } = options
const thresh = LogLevels[level]
const canClearScreen =
allowClearScreen && process.stdout.isTTY && !process.env.CI
const clear = canClearScreen ? clearScreen : () => {}

function format(type: LogType, msg: string, options: LogErrorOptions = {}) {
if (options.timestamp) {
const tag =
type === 'info'
? colors.cyan(colors.bold(prefix))
: type === 'warn'
? colors.yellow(colors.bold(prefix))
: colors.red(colors.bold(prefix))
return `${colors.dim(
getTimeFormatter().format(new Date()),
)} ${tag} ${msg}`
} else {
return msg
}
}

function output(type: LogType, msg: string, options: LogErrorOptions = {}) {
if (thresh >= LogLevels[type]) {
const method = type === 'info' ? 'log' : type
const format = () => {
if (options.timestamp) {
const tag =
type === 'info'
? colors.cyan(colors.bold(prefix))
: type === 'warn'
? colors.yellow(colors.bold(prefix))
: colors.red(colors.bold(prefix))
return `${colors.dim(timeFormatter.format(new Date()))} ${tag} ${msg}`
} else {
return msg
}
}

if (options.error) {
loggedErrors.add(options.error)
}
if (canClearScreen) {
if (type === lastType && msg === lastMsg) {
sameCount++
clear()
console[method](format(), colors.yellow(`(x${sameCount + 1})`))
console[method](
format(type, msg, options),
colors.yellow(`(x${sameCount + 1})`),
)
} else {
sameCount = 0
lastMsg = msg
lastType = type
if (options.clear) {
clear()
}
console[method](format())
console[method](format(type, msg, options))
}
} else {
console[method](format())
console[method](format(type, msg, options))
}
}
}
Expand Down

0 comments on commit 0fb9071

Please sign in to comment.