| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| |
|
| | |
| | |
| | |
| | |
| | function stringify(data: Record<string, any>): string { |
| | let line = '' |
| |
|
| | for (const key in data) { |
| | const value = data[key] |
| | let is_null = false |
| | let stringValue: string |
| |
|
| | if (value == null) { |
| | is_null = true |
| | stringValue = '' |
| | } else { |
| | stringValue = value.toString() |
| | } |
| |
|
| | const needs_quoting = stringValue.indexOf(' ') > -1 || stringValue.indexOf('=') > -1 |
| | const needs_escaping = stringValue.indexOf('"') > -1 || stringValue.indexOf('\\') > -1 |
| |
|
| | if (needs_escaping) { |
| | stringValue = stringValue.replace(/["\\]/g, '\\$&') |
| | } |
| | if (needs_quoting || needs_escaping) { |
| | stringValue = `"${stringValue}"` |
| | } |
| | if (stringValue === '' && !is_null) { |
| | stringValue = '""' |
| | } |
| |
|
| | line += `${key}=${stringValue} ` |
| | } |
| |
|
| | |
| | return line.substring(0, line.length - 1) |
| | } |
| |
|
| | export function toLogfmt(jsonString: Record<string, any>): string { |
| | |
| | const flattenObject = ( |
| | obj: any, |
| | parentKey: string = '', |
| | result: Record<string, any> = {}, |
| | seen: WeakSet<object> = new WeakSet(), |
| | ): Record<string, any> => { |
| | for (const key of Object.keys(obj)) { |
| | const newKey = parentKey ? `${parentKey}.${key}` : key |
| | const value = obj[key] |
| |
|
| | if (value && typeof value === 'object') { |
| | |
| | if (seen.has(value)) { |
| | result[newKey] = '[Circular]' |
| | continue |
| | } |
| |
|
| | |
| | if (value instanceof Date) { |
| | result[newKey] = value.toISOString() |
| | continue |
| | } |
| |
|
| | |
| | if (Array.isArray(value)) { |
| | result[newKey] = value.join(',') |
| | continue |
| | } |
| |
|
| | |
| | const valueKeys = Object.keys(value) |
| | if (valueKeys.length > 0) { |
| | seen.add(value) |
| | flattenObject(value, newKey, result, seen) |
| | seen.delete(value) |
| | } |
| | } else { |
| | |
| | result[newKey] = |
| | value === undefined || (typeof value === 'string' && value === '') ? null : value |
| | } |
| | } |
| | return result |
| | } |
| |
|
| | const flattened = flattenObject(jsonString) |
| |
|
| | return stringify(flattened) |
| | } |
| |
|