1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-25 15:29:32 -05:00

fix(std/log): improve the calculation of byte length (#5819)

This commit is contained in:
zfx 2020-05-29 14:39:33 +08:00 committed by GitHub
parent 6de59f1908
commit 499353ff39
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 4 deletions

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { open, openSync, close, renameSync, statSync } = Deno;
const { open, openSync, close, renameSync, stat } = Deno;
type File = Deno.File;
type Writer = Deno.Writer;
type OpenOptions = Deno.OpenOptions;
@ -142,6 +142,8 @@ interface RotatingFileHandlerOptions extends FileHandlerOptions {
export class RotatingFileHandler extends FileHandler {
#maxBytes: number;
#maxBackupCount: number;
#currentFileSize = 0;
#encoder = new TextEncoder();
constructor(levelName: LevelName, options: RotatingFileHandlerOptions) {
super(levelName, options);
@ -176,6 +178,8 @@ export class RotatingFileHandler extends FileHandler {
);
}
}
} else {
this.#currentFileSize = (await stat(this._filename)).size;
}
}
@ -183,9 +187,12 @@ export class RotatingFileHandler extends FileHandler {
if (this.level > logRecord.level) return;
const msg = this.format(logRecord);
const currentFileSize = statSync(this._filename).size;
if (currentFileSize + msg.length > this.#maxBytes) {
const msgByteLength = this.#encoder.encode(msg).byteLength + 1;
if (this.#currentFileSize + msgByteLength > this.#maxBytes) {
this.rotateLogFiles();
this.#currentFileSize = msgByteLength;
} else {
this.#currentFileSize += msgByteLength;
}
return this.log(msg);

View file

@ -1,6 +1,11 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assert, assertEquals, assertThrowsAsync } from "../testing/asserts.ts";
import {
assert,
assertEquals,
assertThrowsAsync,
assertNotEquals,
} from "../testing/asserts.ts";
import {
LogLevels,
LogLevelNames,
@ -303,3 +308,29 @@ test({
);
},
});
test({
name: "RotatingFileHandler fileSize equal to bytelength of message + 1",
async fn() {
const fileHandler = new RotatingFileHandler("WARNING", {
filename: LOG_FILE,
maxBytes: 100,
maxBackupCount: 1,
mode: "w",
});
await fileHandler.setup();
const msg = "。";
const msgLength = msg.length;
const msgByteLength = new TextEncoder().encode(msg).byteLength;
await fileHandler.log(msg);
const fileSzie = (await Deno.stat(LOG_FILE)).size;
assertEquals(fileSzie, msgByteLength + 1);
assertNotEquals(fileSzie, msgLength);
assertNotEquals(fileSzie, msgLength + 1);
await fileHandler.destroy();
Deno.removeSync(LOG_FILE);
},
});