Skip to content

Commit

Permalink
fix(logger): fix edge case when size exceed
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Dec 17, 2023
1 parent f20e843 commit 4f1f77a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
6 changes: 4 additions & 2 deletions plugins/logger/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@koishijs/plugin-logger",
"description": "Dump log files for Koishi",
"version": "2.6.0",
"version": "2.6.1",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"files": [
Expand Down Expand Up @@ -55,11 +55,13 @@
},
"devDependencies": {
"@koishijs/client": "^5.20.1",
"@types/throttle-debounce": "^2.1.0",
"ansi_up": "^5.2.1",
"koishi": "^4.16.1",
"reggol": "^1.6.3"
},
"dependencies": {
"@koishijs/console": "^5.20.1"
"@koishijs/console": "^5.20.1",
"throttle-debounce": "^3.0.1"
}
}
16 changes: 12 additions & 4 deletions plugins/logger/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { DataService } from '@koishijs/plugin-console'
import { resolve } from 'path'
import { mkdir, readdir, rm } from 'fs/promises'
import { FileWriter } from './file'
import { throttle } from 'throttle-debounce'
import zhCN from './locales/zh-CN.yml'

declare module '@koishijs/plugin-console' {
Expand Down Expand Up @@ -87,6 +88,14 @@ export async function apply(ctx: Context, config: Config) {
const date = new Date().toISOString().slice(0, 10)
createFile(date, Math.max(...files[date] ?? [0]) + 1)

let buffer: Logger.Record[] = []
const update = throttle(100, () => {
// Be very careful about accessing service in this callback,
// because undeclared service access may cause infinite loop.
ctx.get('console.logs')?.patch(buffer)
buffer = []
})

const loader = ctx.get('loader')
const target: Logger.Target = {
colors: 3,
Expand All @@ -103,12 +112,11 @@ export async function apply(ctx: Context, config: Config) {
createFile(date, 1)
}
writer.write(record)
// Be very careful about accessing service in this callback,
// because undeclared service access may cause infinite loop.
ctx.get('console.logs')?.patch([record])
buffer.push(record)
update()
if (writer.size >= config.maxSize) {
writer.close()
const index = Math.max(...files[date]) + 1
const index = Math.max(...files[date] ?? [0]) + 1
files[date].push(index)
createFile(date, index)
}
Expand Down

0 comments on commit 4f1f77a

Please sign in to comment.