Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: console logger #23

Open
wants to merge 2 commits into
base: feat/destructured-constructor
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions benchmark.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env -S npx ts-node
import { performance } from 'perf_hooks'
import { Logger, LogLevel } from './src'
import { LogLevel, StandardLogger } from './src'

// test runner
function run(name: string, fn: () => any, count: number = 1000) {
Expand All @@ -23,15 +23,19 @@ function run(name: string, fn: () => any, count: number = 1000) {
return { name, sum, avg, count }
}

// setup
const NullWriter = () => null
const logger = new Logger({ level: LogLevel.INFO, write: NullWriter })
// return a random log level
const keys = Object.keys(LogLevel).filter((k) => typeof LogLevel[k as keyof typeof LogLevel] === 'number')
const randLevel = () => {
const index = Math.floor(Math.random() * keys.length)
return LogLevel[keys[index] as keyof typeof LogLevel]
}

// run tests
;[
run('simple', () => logger.info('hi')),
run('error', () => logger.info('hi', { error: new Error('fail') })),
run('extra', () => logger.info('hi', { extra: 'abcd' })),
run('with simple', () => logger.with({ with: 'abcd' }).info('hi')),
run('with extra', () => logger.with({ with: 'abcd' }).info('hi', { extra: 'abcd' })),
run('simple', () => StandardLogger.info( 'hi')),
run('error', () => StandardLogger.info( 'hi', { error: new Error('fail') })),
run('extra', () => StandardLogger.info( 'hi', { extra: 'abcd' })),
run('with simple', () => StandardLogger.with({ with: 'abcd' }).info( 'hi')),
run('with extra', () => StandardLogger.with({ with: 'abcd' }).info( 'hi', { extra: 'abcd' })),
run('rainbow level', () => StandardLogger.log( randLevel(), 'thing', { extra: 'abcd' })),
].forEach((a) => console.log(a))
6 changes: 6 additions & 0 deletions example.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/usr/bin/env -S npx ts-node
import { StandardLogger } from './src'
StandardLogger.debug('about to begin')
StandardLogger.warn('cache failure')
StandardLogger.info('user authenticated', { id: '000001' })
StandardLogger.error('failed to complete', { error: new Error('fail') })
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"clean": "rm -rf dist coverage",
"lint": "prettier --write .",
"test": "node --require ts-node/register --test ./src/**/*.test.ts",
"test:watch": "node --require ts-node/register --test --watch ./src/**/*.test.ts",
"prebuild": "npm run clean && npm run lint && npm run test",
"build": "tsc",
"benchmark": "ts-node ./benchmark.ts",
Expand Down
14 changes: 13 additions & 1 deletion src/StandardLogger/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
import { Logger, LogLevel } from '..'
import { JSONSerializer, Logger, LogLevel, Serializer } from '..'
import { ConsoleSerializer } from '../serializers/ConsoleSerializer'

// parse level from env var and set default logger
const level = (process.env.LOG_LEVEL || 'INFO') as keyof typeof LogLevel

// parse format from env var and set default serializer
const serialize = ((format: string): Serializer => {
switch (format.toUpperCase()) {
case 'TEXT':
return ConsoleSerializer()
default:
return JSONSerializer
}
})(process.env.LOG_FORMAT || '')

// StandardLogger is a globally available Logger with a JSON Serializer, timstamps with RFC3339 timestamps, and writer to std out
export const StandardLogger = new Logger({
level: LogLevel[level],
serialize,
})

export default Logger
15 changes: 15 additions & 0 deletions src/serializers/ConsoleSerializer/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import assert from 'node:assert'
import { describe, test } from 'node:test'
import { ConsoleSerializer } from '.'
import { LogLevel } from '../../Logger'

describe(`when serializing`, () => {
const got = ConsoleSerializer({
level: LogLevel[LogLevel.INFO],
message: 'thing happend',
error: new Error('example'),
})
test('should stringify the error', () => {
assert.strictEqual(got, '\x1B[32mINFO\x1B[0m | thing happend\n\t{"error":"Error: example"}')
})
})
44 changes: 44 additions & 0 deletions src/serializers/ConsoleSerializer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { JSONSerializer, LogLevel, Serializer } from '../..'

export enum Colours {
reset = '\u001b[0m',
hicolor = '\u001b[1m',
underline = '\u001b[4m',
inverse = '\u001b[7m',
black = '\u001b[30m',
red = '\u001b[31m',
green = '\u001b[32m',
yellow = '\u001b[33m',
blue = '\u001b[34m',
magenta = '\u001b[35m',
cyan = '\u001b[36m',
white = '\u001b[37m',
bg_black = '\u001b[40m',
bg_red = '\u001b[41m',
bg_green = '\u001b[42m',
bg_yellow = '\u001b[43m',
bg_blue = '\u001b[44m',
bg_magenta = '\u001b[45m',
bg_cyan = '\u001b[46m',
bg_white = '\u001b[47m',
}

export const DefaultColourMap: Map<LogLevel, string> = new Map([
[LogLevel.DEBUG, Colours.bg_cyan + Colours.black],
[LogLevel.INFO, Colours.bg_green + Colours.black],
[LogLevel.WARN, Colours.bg_yellow + Colours.black],
[LogLevel.ERROR, Colours.bg_red + Colours.black],
])

export function wrap(colour: string, key: string): string {
return `${colour}${key}${Colours.reset}`
}

export function ConsoleSerializer(mapping: Map<LogLevel, string> = DefaultColourMap): Serializer {
const colours: Map<string, string> = new Map(Array.from(mapping.entries()).map(([k, v]) => [LogLevel[k], v]))
const mapper = (level: string): string => colours.get(level) || Colours.reset
return (msg: any) => {
const { level, message, ...rest } = msg
return `${wrap(mapper(level), level)} ${message} ${ rest && Object.keys(rest).length ? JSONSerializer(rest) : '' }`
}
}
1 change: 0 additions & 1 deletion src/serializers/JSONSerializer/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ describe(`when serializing errors`, () => {
test('should stringify the error', () => {
const got = JSONSerializer({ error: new Error('example') })
assert.strictEqual(got, `{"error":"Error: example"}`)
assert.strictEqual(1, 1)
})
})

Expand Down
4 changes: 2 additions & 2 deletions src/serializers/JSONSerializer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export const JSONSerializer: Serializer = (msg: any) => JSON.stringify(msg, getC

// getCircularReplacer is Mozilla's suggested approach to dealing with circular references
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value
function getCircularReplacer() {
export function getCircularReplacer() {
const seen = new WeakSet()
return (key: any, value: any) => {
if (typeof value === 'object' && value !== null) {
Expand All @@ -18,7 +18,7 @@ function getCircularReplacer() {
}

// toStringers strigifies some specific types
function toStringers(_: any, value: any) {
export function toStringers(_: any, value: any) {
// exit early for null and undefined
if (value === undefined || value === null) return value

Expand Down