如何使用 Deno 登录文件

how to log to a file with Deno

我不了解 deno 日志记录 api。有人可以解释一下吗? 我正在尝试将所有消息(错误、警告、信息等)记录到一个文件中。最好也有一个时间戳。

这里有一些代码,基本上来自文档中的示例。 没有任何内容 正在写入日志文件。

import * as log from "https://deno.land/std/log/mod.ts";

async function startLogger() {
  await log.setup({
    handlers: {
      console: new log.handlers.ConsoleHandler("DEBUG"),

      file: new log.handlers.FileHandler("WARNING", {
        filename: "./logTest.txt",
        // you can change format of output message using any keys in `LogRecord`
        formatter: "{levelName} {msg}",
      }),
    },

    loggers: {
      // configure default logger available via short-hand methods above
      default: {
        level: "DEBUG",
        handlers: ["console", "file"],
      },

      tasks: {
        level: "ERROR",
        handlers: ["console"],
      },
    },
  });
      // get default logger
      const logger = log.getLogger();
      return logger
}

var logger = await startLogger()

logger.debug('debug should this show up in a file?')
logger.error('error should this show up in a file?')
logger.warning('warn should this show up in a file?')
logger.info('warn should this show up in a file?')

deno run --allow-write --allow-read testLogger.js

FileHandler 每 30 秒刷新一次磁盘。如果您等待 30 秒,您将看到正在写入数据。

来自文档:

This handler uses a buffer for writing to file and will automatically flush every 30 seconds, though you can trigger this yourself with fileHandler.flush(). Log messages with a log level greater than error are immediately flushed.