Skip to content

Commit

Permalink
feat: date format
Browse files Browse the repository at this point in the history
Signed-off-by: luoling8192 <[email protected]>
  • Loading branch information
luoling8192 committed Nov 26, 2024
1 parent a5d8757 commit 19c5993
Show file tree
Hide file tree
Showing 6 changed files with 77 additions and 17 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
"test:run": "vitest run"
},
"dependencies": {
"chalk": "^5.3.0"
"chalk": "^5.3.0",
"date-fns": "^4.1.0"
},
"devDependencies": {
"@antfu/eslint-config": "2.21",
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

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

2 changes: 2 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,5 @@ export const availableLogLevels: LogLevel[] = [
]

export const availableFormats: Format[] = [Format.JSON, Format.Pretty]

export const DEFAULT_TIME_FORMAT = 'yyyy-MM-dd HH:mm:ss'
49 changes: 40 additions & 9 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Format, LogLevel, LogLevelString } from './types'
import {
DEFAULT_TIME_FORMAT,
availableFormats,
availableLogLevelStrings,
availableLogLevels,
Expand All @@ -23,6 +24,8 @@ const GLOBAL_CONFIG = {
configured: false,
logLevel: LogLevel.Debug,
format: Format.JSON,
// eslint-disable-next-line ts/no-unsafe-assignment
timeFormat: DEFAULT_TIME_FORMAT,
}

export function getGlobalLogLevel(): LogLevel {
Expand Down Expand Up @@ -82,6 +85,16 @@ export function setGlobalFormat(format: Format): void {
GLOBAL_CONFIG.configured = true
}

export function setGlobalTimeFormat(timeFormat: string): void {
GLOBAL_CONFIG.timeFormat = timeFormat
GLOBAL_CONFIG.configured = true
}

export function getGlobalTimeFormat(): string {
// eslint-disable-next-line ts/no-unsafe-return
return GLOBAL_CONFIG.timeFormat
}

interface Logger {
/**
*
Expand Down Expand Up @@ -205,6 +218,11 @@ interface Logger {
* @returns
*/
warn: (message: any, ...optionalParams: [...any, string?]) => void
/**
* Sets the time format for log timestamps
* @param format - date-fns compatible format string
*/
withTimeFormat: (format: string) => Logger
}

interface InternalLogger extends Logger {
Expand All @@ -213,6 +231,7 @@ interface InternalLogger extends Logger {
logLevel: LogLevel
format: Format
shouldUseGlobalConfig: boolean
timeFormat: string
}

export function createLogg(context: string): Logger {
Expand All @@ -222,6 +241,8 @@ export function createLogg(context: string): Logger {
logLevel: LogLevel.Debug,
format: Format.JSON,
shouldUseGlobalConfig: false,
// eslint-disable-next-line ts/no-unsafe-assignment
timeFormat: DEFAULT_TIME_FORMAT,
useGlobalConfig: (): Logger => {
logObj.shouldUseGlobalConfig = true
logObj.format = getGlobalFormat()
Expand Down Expand Up @@ -390,6 +411,7 @@ export function createLogg(context: string): Logger {
logObj.fields,
// eslint-disable-next-line ts/no-unsafe-argument
message,
logObj.shouldUseGlobalConfig ? getGlobalTimeFormat() : logObj.timeFormat,
// eslint-disable-next-line ts/no-unsafe-argument
...optionalParams,
)
Expand All @@ -402,7 +424,8 @@ export function createLogg(context: string): Logger {
console.debug(logObj.fields)
// eslint-disable-next-line no-console
console.groupEnd()
} else {
}
else {
// eslint-disable-next-line no-console
console.debug(format === Format.JSON ? JSON.stringify(raw) : toPrettyString(raw))
}
Expand Down Expand Up @@ -445,6 +468,7 @@ export function createLogg(context: string): Logger {
logObj.fields,
// eslint-disable-next-line ts/no-unsafe-argument
message,
logObj.shouldUseGlobalConfig ? getGlobalTimeFormat() : logObj.timeFormat,
// eslint-disable-next-line ts/no-unsafe-argument
...optionalParams,
)
Expand Down Expand Up @@ -497,6 +521,7 @@ export function createLogg(context: string): Logger {
logObj.fields,
// eslint-disable-next-line ts/no-unsafe-argument
message,
logObj.shouldUseGlobalConfig ? getGlobalTimeFormat() : logObj.timeFormat,
// eslint-disable-next-line ts/no-unsafe-argument
...optionalParams,
)
Expand Down Expand Up @@ -550,6 +575,7 @@ export function createLogg(context: string): Logger {
// eslint-disable-next-line ts/no-unsafe-argument
message,
stack,
logObj.shouldUseGlobalConfig ? getGlobalTimeFormat() : logObj.timeFormat,
// eslint-disable-next-line ts/no-unsafe-argument
...optionalParams,
)
Expand All @@ -558,7 +584,6 @@ export function createLogg(context: string): Logger {
// eslint-disable-next-line no-console
console.group(format === Format.JSON ? JSON.stringify(raw) : toPrettyString(raw))
if (Object.keys(logObj.fields).length > 0) {
// eslint-disable-next-line no-console
console.error(logObj.fields)
}
// eslint-disable-next-line no-console
Expand All @@ -568,15 +593,15 @@ export function createLogg(context: string): Logger {

switch (format) {
case Format.JSON:
// eslint-disable-next-line no-console

console.error(JSON.stringify(raw))
break
case Format.Pretty:
// eslint-disable-next-line no-console

console.error(toPrettyString(raw))
break
default:
// eslint-disable-next-line no-console

console.error(JSON.stringify(raw))
break
}
Expand Down Expand Up @@ -607,6 +632,7 @@ export function createLogg(context: string): Logger {
logObj.fields,
// eslint-disable-next-line ts/no-unsafe-argument
message,
logObj.shouldUseGlobalConfig ? getGlobalTimeFormat() : logObj.timeFormat,
// eslint-disable-next-line ts/no-unsafe-argument
...optionalParams,
)
Expand All @@ -615,7 +641,6 @@ export function createLogg(context: string): Logger {
// eslint-disable-next-line no-console
console.group(format === Format.JSON ? JSON.stringify(raw) : toPrettyString(raw))
if (Object.keys(logObj.fields).length > 0) {
// eslint-disable-next-line no-console
console.warn(logObj.fields)
}
// eslint-disable-next-line no-console
Expand All @@ -625,19 +650,25 @@ export function createLogg(context: string): Logger {

switch (format) {
case Format.JSON:
// eslint-disable-next-line no-console

console.warn(JSON.stringify(raw))
break
case Format.Pretty:
// eslint-disable-next-line no-console

console.warn(toPrettyString(raw))
break
default:
// eslint-disable-next-line no-console

console.warn(JSON.stringify(raw))
break
}
},

withTimeFormat: (format: string): Logger => {
const logger = logObj.child() as InternalLogger
logger.timeFormat = format
return logger
},
}

return logObj
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,5 @@ export interface Log {

export interface LoggerConfig {
forceColors?: boolean
timeFormat?: string
}
31 changes: 24 additions & 7 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import chalk from 'chalk'

import { logLevelStringToLogLevelMap, logLevelToChalkColorMap } from './constants'
import { format, formatISO } from 'date-fns'
import { DEFAULT_TIME_FORMAT, logLevelStringToLogLevelMap, logLevelToChalkColorMap } from './constants'
import type { Log, LogLevelString, LoggerConfig } from './types'
import { LogLevel } from './types'

Expand Down Expand Up @@ -29,7 +29,15 @@ export function isErrorLike(err: unknown): err is ErrorLike {
return false
}

export function newLog(logLevel: LogLevelString, context: string, fields: Record<string, any>, message: string, ...optionalParams: [...any, string?]): Log {
export function newLog(
logLevel: LogLevelString,
context: string,
fields: Record<string, any>,
message: string,
// eslint-disable-next-line ts/no-unsafe-assignment
timeFormat: string = DEFAULT_TIME_FORMAT,
...optionalParams: [...any, string?]
): Log {
let fieldsObj: { context?: string, [key: string]: any } = { context: '' }

if (typeof fields !== 'undefined' && fields !== null) {
Expand All @@ -49,8 +57,8 @@ export function newLog(logLevel: LogLevelString, context: string, fields: Record
}

const raw: Log = {
'@timestamp': new Date().toISOString(),
'@localetime': new Date().toLocaleString(),
'@timestamp': formatISO(new Date()),
'@localetime': format(new Date(), timeFormat),
'level': logLevel,
'fields': fieldsObj,
'message': messageString,
Expand All @@ -59,9 +67,18 @@ export function newLog(logLevel: LogLevelString, context: string, fields: Record
return raw
}

export function newErrorLog(logLevel: LogLevelString, context: string, fields: Record<string, any>, message: string, errorStack?: string, ...optionalParams: [...any, string?]): Log {
export function newErrorLog(
logLevel: LogLevelString,
context: string,
fields: Record<string, any>,
message: string,
errorStack?: string,
// eslint-disable-next-line ts/no-unsafe-assignment
timeFormat: string = DEFAULT_TIME_FORMAT,
...optionalParams: [...any, string?]
): Log {
// eslint-disable-next-line ts/no-unsafe-argument
const log = newLog(logLevel, context, fields, message, ...optionalParams)
const log = newLog(logLevel, context, fields, message, timeFormat, ...optionalParams)
if (typeof errorStack !== 'undefined' && errorStack !== null) {
log.errored = true
log.error = { stack: errorStack }
Expand Down

0 comments on commit 19c5993

Please sign in to comment.