Skip to content

Commit

Permalink
test(buildlogmessage): check ansi
Browse files Browse the repository at this point in the history
  • Loading branch information
PunGrumpy committed Sep 18, 2024
1 parent 32e8328 commit 82a5c77
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 7 deletions.
18 changes: 13 additions & 5 deletions src/core/buildLogMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ import {
const defaultLogFormat =
'🦊 {now} {level} {duration} {method} {pathname} {status} {message} {ip}'

function shouldUseColors(useColors: boolean, options?: Options): boolean {
if (options?.config?.useColors !== undefined) {
return options.config.useColors && process.env.NO_COLOR === undefined
}
return useColors && process.env.NO_COLOR === undefined
}

export function buildLogMessage(
level: LogLevel,
request: RequestInfo,
Expand All @@ -27,17 +34,18 @@ export function buildLogMessage(
options?: Options,
useColors: boolean = true
): string {
const actuallyUseColors = shouldUseColors(useColors, options)
const now = new Date()
const components: LogComponents = {
now: useColors
now: actuallyUseColors
? chalk.bgYellow(chalk.black(now.toLocaleString()))
: now.toLocaleString(),
epoch: Math.floor(now.getTime() / 1000).toString(),
level: logString(level, useColors),
duration: durationString(store.beforeTime, useColors),
method: methodString(request.method, useColors),
level: logString(level, actuallyUseColors),
duration: durationString(store.beforeTime, actuallyUseColors),
method: methodString(request.method, actuallyUseColors),
pathname: pathString(request),
status: statusString(data.status || 200, useColors),
status: statusString(data.status || 200, actuallyUseColors),
message: data.message || '',
ip:
options?.config?.ip && request.headers.get('x-forwarded-for')
Expand Down
1 change: 1 addition & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ export interface Options {
status?: number | number[]
} | null
ip?: boolean
useColors?: boolean
showBanner?: boolean
transports?: Transport[]
}
Expand Down
14 changes: 12 additions & 2 deletions tests/core/buildLogMessage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@ test('buildLogMessage', () => {
true
)

expect(colorMessage).not.toBe(message)
expect(colorMessage.split(' ')[0]).not.toBe(message.split(' ')[0])
expect(colorMessage).toContain('INFO')
expect(colorMessage).toContain('Test message')
expect(colorMessage).toContain('127.0.0.1')

const hasAnsiCodes = /\\x1B\[[0-9;]*m/.test(colorMessage)
if (hasAnsiCodes) {
expect(colorMessage).not.toBe(message)
} else {
console.warn(
'No ANSI color codes detected. Colors might be disabled in this environment.'
)
}
})

0 comments on commit 82a5c77

Please sign in to comment.