-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(logger): update dump strategy, fix #50
- Loading branch information
Showing
3 changed files
with
144 additions
and
72 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import { FileHandle, open } from 'fs/promises' | ||
import { Logger } from 'koishi' | ||
|
||
export class FileWriter { | ||
public data: Logger.Record[] | ||
public task: Promise<FileHandle> | ||
public size: number | ||
|
||
private temp: Logger.Record[] = [] | ||
|
||
constructor(public date: string, public path: string) { | ||
this.task = open(path, 'a+').then(async (handle) => { | ||
const buffer = await handle.readFile() | ||
this.data = this.parse(new TextDecoder().decode(buffer)) | ||
this.size = buffer.byteLength | ||
return handle | ||
}) | ||
this.task.then(() => this.flush()) | ||
} | ||
|
||
flush() { | ||
if (!this.temp.length) return | ||
this.task = this.task.then(async (handle) => { | ||
const content = Buffer.from(this.temp.map((record) => JSON.stringify(record) + '\n').join('')) | ||
await handle.write(content) | ||
this.data.push(...this.temp) | ||
this.size += content.byteLength | ||
this.temp = [] | ||
return handle | ||
}) | ||
} | ||
|
||
parse(text: string) { | ||
return text.split('\n').map((line) => { | ||
try { | ||
return JSON.parse(line) | ||
} catch {} | ||
}).filter(Boolean) | ||
} | ||
|
||
async read() { | ||
await this.task | ||
return this.data | ||
} | ||
|
||
write(record: Logger.Record) { | ||
this.temp.push(record) | ||
this.flush() | ||
} | ||
|
||
async close() { | ||
const handle = await this.task | ||
await handle.close() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters