Skip to content

Commit

Permalink
fix: expose toJson serialization function
Browse files Browse the repository at this point in the history
fix: httpLogs, allow overwriting Log class

chore: add common js test on transpiled js in /lib
  • Loading branch information
commenthol committed Oct 7, 2023
1 parent 8af9c53 commit 905b6c8
Show file tree
Hide file tree
Showing 10 changed files with 51 additions and 13 deletions.
7 changes: 7 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"tabWidth": 2,
"useTabs": false,
"singleQuote": true,
"semi": false,
"trailingComma": "none"
}
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ log.debug({ object: 1 }) // ...
| sonicFlushMs | DEBUG_SONIC_FLUSH_MS | node | number | flush after each x ms (default is 1000) |
| serializers | -- | _both_ | Object | serializers by keys |
| url | DEBUG_URL | browser | String | |
| toJson | -- | node | Function | custom json serializer |

### Serializers

Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -99,5 +99,8 @@
},
"engines": {
"node": ">=12"
},
"c4uIgnore": {
"chalk": "^4; ^5 is ESM only and won't work with transpiled version"
}
}
6 changes: 4 additions & 2 deletions src/httpLogs.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,17 @@ const serializers = {

/**
* @param {string} [namespace='debug-level:http']
* @param {LogOptionsHttpLog} [opts]
* @param {LogOptionsHttpLog & {Log: Log}} [opts]
* @returns {(req: IncomingMessageWithId, res: ServerResponse, next: Function) => void} connect middleware
*/
export function httpLogs (namespace, opts) {
const options = {
Log,
serializers,
...opts
}
const log = new Log(namespace || 'debug-level:http', options)
// @ts-expect-error
const log = new options.Log(namespace || 'debug-level:http', options)
const generateId = options.customGenerateRequestId || generateRequestId

return function _httpLogs (req, res, next) {
Expand Down
9 changes: 5 additions & 4 deletions src/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const options = {
sonicFlushMs: 1000, // min. timeout before write
spaces: undefined, // pretty print JSON
splitLine: isDevEnv, // split lines for pretty debug like output
serializers: { err: errSerializer }
serializers: { err: errSerializer } // serializers definition
}

export class Log extends LogBase {
Expand All @@ -71,6 +71,7 @@ export class Log extends LogBase {
this.levColors = levelColors(colorFn)
// noop for TS
this.opts = { ..._opts, ...this.opts }
this.toJson = toJson

this.stream = this.opts.sonic
? new Sonic(this.opts.stream, {
Expand Down Expand Up @@ -198,7 +199,7 @@ export class Log extends LogBase {
*/
_log (level, fmt, args) {
const o = this._formatJson(level, fmt, args)
const str = toJson(o, this.serializers)
const str = this.toJson(o, this.serializers)
return this.render(str, level)
}

Expand All @@ -208,7 +209,7 @@ export class Log extends LogBase {
*/
_logJsonColor (level, fmt, args) {
const o = this._formatJson(level, fmt, args)
let str = toJson(o, this.serializers)
let str = this.toJson(o, this.serializers)
/* c8 ignore next 4 */ // can't cover with tests as underlying tty is unknown
str = str
.replace(/"level":\s?"([^"]+)"/, (m, level) => this._color(m, this.levColors[level], true))
Expand Down Expand Up @@ -350,7 +351,7 @@ function toJson (obj, serializers, spaces) {
* @param {number} [spaces]
* @returns {string}
*/
function stringify (any, spaces) {
export function stringify (any, spaces) {
try {
return JSON.stringify(any, null, spaces)
} catch (e) {
Expand Down
2 changes: 1 addition & 1 deletion src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export const inspectOpts = (obj) => Object.keys(obj)

export const saveOpts = (obj, options) => {
Object.keys(options).forEach((prop) => {
if (['stream', 'serializers'].includes(prop)) return // do not safe stream option
if (['stream', 'serializers', 'toJson'].includes(prop)) return // do not safe stream option
let key = 'DEBUG_' + prop.replace(/([A-Z])/g, (_, prop) => '_' + prop.toLowerCase())
if (prop === 'namespaces') key = 'DEBUG'
key = key.toUpperCase()
Expand Down
8 changes: 8 additions & 0 deletions test/commonjs.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const { Log } = require('../lib/node.cjs')

describe('commonjs', function () {
it('shall log', function () {
const log = new Log('test')
log.error('log with cjs')
})
})
8 changes: 4 additions & 4 deletions test/node.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ const reset = () => {
Log.reset()
}

describe('#Log node', function () {
describe('Log node', function () {
describe('options', function () {
after(reset)

it('should get default options', function () {
const { stream, serializers, ...res } = Log.options()
const { stream, serializers, toJson, ...res } = Log.options()
assert.deepStrictEqual(res, {
level: 'INFO',
namespaces: undefined,
Expand All @@ -44,7 +44,7 @@ describe('#Log node', function () {

it('should set options', function () {
Log.options({ level: 'error', json: true, colors: false, namespaces: 'foo*,bar' })
const { stream, serializers, ...res } = Log.options()
const { stream, serializers, toJson, ...res } = Log.options()
assert.deepStrictEqual(res, {
level: 'error',
namespaces: 'foo*,bar',
Expand Down Expand Up @@ -490,7 +490,7 @@ describe('#Log node', function () {
})

describe('serializers', function () {
it('shall log with defaut err serializer', function () {
it('shall log with default err serializer', function () {
const log = new Log('serialize', { json: true, colors: false })
const err = new Error('baamm')
err.stack = 'Error: baam\n at Context.<anonymous>'
Expand Down
6 changes: 4 additions & 2 deletions types/httpLogs.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@
*/
/**
* @param {string} [namespace='debug-level:http']
* @param {LogOptionsHttpLog} [opts]
* @param {LogOptionsHttpLog & {Log: Log}} [opts]
* @returns {(req: IncomingMessageWithId, res: ServerResponse, next: Function) => void} connect middleware
*/
export function httpLogs(namespace?: string | undefined, opts?: LogOptionsHttpLog | undefined): (req: IncomingMessageWithId, res: ServerResponse, next: Function) => void;
export function httpLogs(namespace?: string | undefined, opts?: (import("./Format.js").FormatOption & import("./LogBase.js").ExtLogBaseOptions & import("./node.js").ExtLogOptions & ExtLogOptionsHttpLog & {
Log: Log;
}) | undefined): (req: IncomingMessageWithId, res: ServerResponse, next: Function) => void;
export type IncomingMessage = import('node:http').IncomingMessage;
export type ServerResponse = import('node:http').ServerResponse;
export type LogOptions = import('./node.js').LogOptions;
Expand Down
14 changes: 14 additions & 0 deletions types/node.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
/**
* @param {any} any
* @param {number} [spaces]
* @returns {string}
*/
export function stringify(any: any, spaces?: number | undefined): string;
export class Log extends LogBase {
/**
* Apply (and get) global options
Expand Down Expand Up @@ -110,6 +116,7 @@ export class Log extends LogBase {
*/
sonicFlushMs?: number | undefined;
};
toJson: typeof toJson;
stream: NodeJS.WriteStream | Sonic;
/**
* format object to json
Expand Down Expand Up @@ -171,6 +178,13 @@ export type ExtLogOptions = {
};
export type LogOptions = LogBaseOptions & ExtLogOptions;
import { LogBase } from "./LogBase.js";
/**
* @param {object} obj
* @param {object} serializers
* @param {number} [spaces]
* @returns {string}
*/
declare function toJson(obj: object, serializers: object, spaces?: number | undefined): string;
import { Sonic } from "./Sonic.js";
declare const isDevEnv: boolean;
export {};

0 comments on commit 905b6c8

Please sign in to comment.