Skip to content

Commit

Permalink
dlog: pretty print multiline only on dev mode (#590)
Browse files Browse the repository at this point in the history
This PR changes the dlog implementation to print multiline only in dev
mode.
Hoping to fix the issue with logging services like Datadog where we had
each line in a different log

Closes #544
  • Loading branch information
miguel-nascimento authored Aug 1, 2024
1 parent a5f49a2 commit 38988a5
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
2 changes: 1 addition & 1 deletion packages/dlog/src/check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export class CodeException extends Error {

export function throwWithCode(message?: string, code?: Err, data?: any): never {
const e = new CodeException(message ?? 'Unknown', code ?? Err.ERR_UNSPECIFIED, data)
log('throwWithCode', e.message, e.stack)
log('throwWithCode', e)
throw e
}

Expand Down
8 changes: 5 additions & 3 deletions packages/dlog/src/dlog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ export interface DLogOpts {

const allDlogs: Map<string, DLogger> = new Map()

const isDev = typeof process !== 'undefined' && process.env.NODE_ENV === 'development'

const makeDlog = (d: Debugger, opts?: DLogOpts): DLogger => {
if (opts?.printStack) {
// eslint-disable-next-line no-console
Expand All @@ -166,14 +168,14 @@ const makeDlog = (d: Debugger, opts?: DLogOpts): DLogger => {
newArgs.push(c)
} else if (typeof c === 'object' && c !== null) {
if (c instanceof Error) {
tailArgs.push('\n')
isDev ? fmt.push('%O\n') : fmt.push('%o\n')
tailArgs.push(c)
} else {
fmt.push('%O\n')
isDev ? fmt.push('%O\n') : fmt.push('%o\n')
newArgs.push(cloneAndFormat(c, { shortenHex: true }))
}
} else {
fmt.push('%O ')
isDev ? fmt.push('%O ') : fmt.push('%o ')
newArgs.push(c)
}
}
Expand Down
18 changes: 18 additions & 0 deletions packages/dlog/src/tests/dlog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import { dlog, dlogError } from '../dlog'
import debug from 'debug'
import { bin_fromHexString } from '../binary'
import { CodeException } from '../check'
import { Err } from '@river-build/proto'

describe('dlogTest', () => {
test('basic', () => {
Expand Down Expand Up @@ -211,4 +213,20 @@ describe('dlogTest', () => {
log = dlog(ns, { defaultEnabled: true, allowJest: true })
expect(log.enabled).toBeFalsy()
})

test('handle error', () => {
const e = new CodeException('test', Err.ERR_UNSPECIFIED)
const log = dlogError('test:dlog')
log.enabled = true

let output: string = ''
log.baseDebug.log = (...args: any[]) => {
for (const arg of args) {
output += `${arg}`
}
}

log('throwWithCode', e)
expect(output).toContain('CodeException [Error]: test at Object.<anonymous>')
})
})

0 comments on commit 38988a5

Please sign in to comment.