Skip to content

Commit

Permalink
feat(core): built-in debug logger
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Jan 13, 2020
1 parent e67b817 commit fa5c46e
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 35 deletions.
10 changes: 3 additions & 7 deletions packages/koishi-core/src/app.ts
@@ -1,4 +1,3 @@
import debug from 'debug'
import escapeRegex from 'escape-string-regexp'
import { Sender } from './sender'
import { Server, createServer, ServerType } from './server'
Expand All @@ -25,9 +24,6 @@ export interface AppOptions {
similarityCoefficient?: number
}

const showLog = debug('koishi')
const showReceiverLog = debug('koishi:receiver')

const selfIds = new Set<number>()
export const appMap: Record<number, App> = {}
export const appList: App[] = []
Expand Down Expand Up @@ -222,7 +218,7 @@ export class App extends Context {
tasks.push(this.server.listen())
}
await Promise.all(tasks)
showLog('started')
this.logger('app').debug('started')
this.receiver.emit('connect')
if (this.selfId && !this._isReady) {
this.receiver.emit('ready')
Expand All @@ -242,15 +238,15 @@ export class App extends Context {
if (this.server) {
this.server.close()
}
showLog('stopped')
this.logger('app').debug('stopped')
this.receiver.emit('disconnect')
}

emitEvent <K extends Events> (meta: Meta, event: K, ...payload: Parameters<EventMap[K]>) {
for (const path in this._contexts) {
const context = this._contexts[path]
if (!context.match(meta)) continue
showReceiverLog(path, 'emits', event)
this.logger('receiver').debug(path, 'emits', event)
context.receiver.emit(event, ...payload)
}
}
Expand Down
5 changes: 1 addition & 4 deletions packages/koishi-core/src/command.ts
Expand Up @@ -4,7 +4,6 @@ import { messages, errors } from './messages'
import { noop } from 'koishi-utils'
import { MessageMeta } from './meta'
import { format } from 'util'
import debug from 'debug'

import {
CommandOption,
Expand All @@ -16,8 +15,6 @@ import {
ParsedLine,
} from './parser'

const showCommandLog = debug('koishi:command')

export interface ParsedCommandLine extends Partial<ParsedLine> {
meta: MessageMeta
command?: Command
Expand Down Expand Up @@ -286,7 +283,7 @@ export class Command {
if (!await this._checkUser(meta, options)) return

// execute command
showCommandLog('execute %s', this.name)
this.context.logger('command').debug('execute %s', this.name)
this.app.emitEvent(meta, 'command', argv)

let skipped = false
Expand Down
7 changes: 2 additions & 5 deletions packages/koishi-core/src/sender.ts
@@ -1,4 +1,3 @@
import debug from 'debug'
import axios from 'axios'
import { snakeCase, camelCase, isInteger } from 'koishi-utils'
import { WsClient } from './server'
Expand All @@ -20,8 +19,6 @@ import {
ContextType,
} from './meta'

const showSenderLog = debug('koishi:sender')

export class SenderError extends Error {
readonly name = 'SenderError'

Expand Down Expand Up @@ -68,9 +65,9 @@ export class Sender {
}

async get <T = any> (action: string, params: Record<string, any> = {}, silent = false): Promise<T> {
showSenderLog('request %s %o', action, params)
this.app.logger('sender').debug('request %s %o', action, params)
const response = await this._get(action, snakeCase(params))
showSenderLog('response %o', response)
this.app.logger('sender').debug('response %o', response)
const { data, retcode } = response
if (retcode === 0 && !silent) {
return camelCase(data)
Expand Down
42 changes: 23 additions & 19 deletions packages/koishi-core/src/server.ts
@@ -1,5 +1,4 @@
import WebSocket from 'ws'
import debug from 'debug'
import * as http from 'http'
import { errors } from './messages'
import { createHmac } from 'crypto'
Expand All @@ -9,11 +8,6 @@ import { App } from './app'
import { CQResponse } from './sender'
import { format } from 'util'

const showServerLog = debug('koishi:server')

// @ts-ignore: @types/debug does not include the property
showServerLog.inspectOpts.depth = 0

export abstract class Server {
public appList: App[] = []
public version: VersionInfo
Expand All @@ -27,11 +21,22 @@ export abstract class Server {
this.bind(app)
}

/**
* representative app
*/
get app () {
return this.appList[0]
}

protected debug (format: any, ...params: any[]) {
this.app?.logger('sender').debug(format, ...params)
}

protected prepareMeta (data: any) {
const meta = camelCase<Meta>(data)
if (!meta.selfId) {
// below version 3.4
meta.selfId = this.appList[0].selfId
meta.selfId = this.app.selfId
} else if (!this.appMap[meta.selfId]) {
const app = this.appList.find(app => !app.options.selfId)
if (!app) return
Expand Down Expand Up @@ -219,7 +224,7 @@ export class HttpServer extends Server {

// no matched application
const data = JSON.parse(body)
showServerLog('receive %o', data)
this.debug('receive %o', data)
const meta = this.prepareMeta(data)
if (!meta) {
res.statusCode = 403
Expand Down Expand Up @@ -251,20 +256,20 @@ export class HttpServer extends Server {
}

async _listen () {
showServerLog('http server opening')
const { port } = this.appList[0].options
this.debug('http server opening')
const { port } = this.app.options
this.server.listen(port)
try {
this.version = await this.appList[0].sender.getVersionInfo()
this.version = await this.app.sender.getVersionInfo()
} catch (error) {
throw new Error('authorization failed')
}
showServerLog('http server listen to', port)
this.debug('http server listen to', port)
}

_close () {
this.server.close()
showServerLog('http server closed')
this.debug('http server closed')
}
}

Expand All @@ -286,9 +291,9 @@ export class WsClient extends Server {

_listen (): Promise<void> {
return new Promise((resolve, reject) => {
showServerLog('websocket client opening')
this.debug('websocket client opening')
const headers: Record<string, string> = {}
const { token, server } = this.appList[0].options
const { token, server } = this.app.options
if (token) headers.Authorization = `Bearer ${token}`
this.socket = new WebSocket(server, { headers })

Expand All @@ -305,7 +310,7 @@ export class WsClient extends Server {
let resolved = false
this.socket.on('message', (data) => {
data = data.toString()
showServerLog('receive', data)
this.debug('receive', data)
let parsed: any
try {
parsed = JSON.parse(data)
Expand All @@ -314,8 +319,7 @@ export class WsClient extends Server {
}
if (!resolved) {
resolved = true
const { server } = this.appList[0].options
showServerLog('connect to ws server:', server)
this.debug('connect to ws server:', this.app.options.server)
resolve()
}
if ('post_type' in parsed) {
Expand All @@ -334,7 +338,7 @@ export class WsClient extends Server {

_close () {
this.socket.close()
showServerLog('websocket client closed')
this.debug('websocket client closed')
}
}

Expand Down

0 comments on commit fa5c46e

Please sign in to comment.