Skip to content
This repository has been archived by the owner on May 19, 2023. It is now read-only.

Commit

Permalink
feat(core): improved logging for additional objects
Browse files Browse the repository at this point in the history
Now you can pass to functions like debug() additional objects that will
get formatted and logged with NodeJS's utils.inspect function
  • Loading branch information
AuHau committed May 14, 2020
1 parent 258bcb3 commit a9576fb
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import colors from 'colors'
import config from 'config'

import { Logger } from './definitions'
import { inspect } from 'util'

// Inspired from https://github.com/visionmedia/debug
const names: RegExp[] = []
Expand Down Expand Up @@ -112,7 +113,7 @@ function initLogging (): void {
// To see more detailed errors, change this to 'debug'
level: config.get('log.level') || 'info',
format: format.combine(
format.splat(),
// format.splat(),
format.metadata(),
filterServices(),
upperCaseLevel(),
Expand All @@ -121,11 +122,20 @@ function initLogging (): void {
format.timestamp({ format: 'DD/MM hh:mm:ss' }),
format.colorize(),
format.printf(info => {
if (info.metadata.service) {
return `[${info.level}] ${colors.grey(info.timestamp)} (${info.metadata.service}): ${info.message}`
let message: string
const { service, ...rest } = info.metadata

if (service) {
message = `[${info.level}] ${colors.grey(info.timestamp)} (${service}): ${info.message}`
} else {
return `[${info.level}] ${colors.grey(info.timestamp)}: ${info.message}`
message = `[${info.level}] ${colors.grey(info.timestamp)}: ${info.message}`
}

if (Object.keys(rest).length > 0) {
message += '\n' + Object.values(rest).map(e => inspect(e, false, 2, true)).join('\n')
}

return message
})
),
transports: transportsSet
Expand All @@ -134,7 +144,7 @@ function initLogging (): void {

type SupportedLevels = 'error' | 'warn' | 'info' | 'verbose' | 'debug'

function delayedLoggingMethod (level: SupportedLevels, name?: string): (message: string, ...meta: any[]) => void {
function delayedLoggingMethod (level: SupportedLevels, name?: string) {
return function (message: string, ...meta: any[]): void {
// First logging call, lets setup logging
if (!mainLogger) {
Expand All @@ -146,9 +156,9 @@ function delayedLoggingMethod (level: SupportedLevels, name?: string): (message:
loggers[name] = mainLogger.child({ service: name })
}

loggers[name][level](message, ...meta)
loggers[name].log(level, message, ...meta)
} else {
mainLogger[level](message, ...meta)
mainLogger.log(level, message, ...meta)
}
}
}
Expand Down

0 comments on commit a9576fb

Please sign in to comment.