Skip to content

Commit

Permalink
feat(utils): support logger.stream
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Sep 5, 2020
1 parent 134df60 commit 91ceff7
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
6 changes: 4 additions & 2 deletions packages/koishi-utils/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ export class Logger {
private code: number
private displayName: string

constructor(private name: string, private showDiff = false) {
public stream: NodeJS.WritableStream = process.stderr

constructor(public name: string, private showDiff = false) {
if (name in instances) return instances[name]
let hash = 0
for (let i = 0; i < name.length; i++) {
Expand All @@ -72,7 +74,7 @@ export class Logger {
private createMethod(name: LogType, prefix: string, minLevel: number) {
this[name] = (...args: [any, ...any[]]) => {
if (this.level < minLevel) return
process.stderr.write(prefix + this.displayName + this.format(...args) + '\n')
this.stream.write(prefix + this.displayName + this.format(...args) + '\n')
}
}

Expand Down
54 changes: 54 additions & 0 deletions packages/koishi-utils/tests/logger.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { install, InstalledClock } from '@sinonjs/fake-timers'
import { expect } from 'chai'
import { Logger } from 'koishi-utils'
import { Writable } from 'stream'

describe('Logger API', () => {
let logger: Logger
let data: string
let clock: InstalledClock
const { colors } = Logger.options

before(() => {
Logger.options.colors = false
clock = install({ now: Date.now() })
})

after(() => {
Logger.options.colors = colors
clock.uninstall()
})

it('basic support', () => {
logger = new Logger('test').extend('logger', true)
expect(logger.name).to.equal('test:logger')
logger.stream = new Writable({
write(chunk, encoding, callback) {
data = chunk.toString()
callback()
},
})
})

it('format error', () => {
const error = new Error('message')
error.stack = null
logger.error(error)
expect(data).to.equal('[E] test:logger message\n')
})

it('format object', () => {
clock.tick(2)
const object = { foo: 'bar' }
logger.success(object)
expect(data).to.equal("[S] test:logger { foo: 'bar' } +2ms\n")
})

it('custom formatter', () => {
clock.tick(1)
Logger.formatters.x = () => 'custom'
Logger.levels[logger.name] = 2
logger.info('%x%%x')
expect(data).to.equal('[I] test:logger custom%x +1ms\n')
})
})

0 comments on commit 91ceff7

Please sign in to comment.