how to log to a file with Deno

Viewed 687

I do not understand the deno logging api. Can someone explain it? I am trying to log all of my messages(error, warning, info, etc...) to a single file. It would be nice to have a time stamp too.

Here is some code which is basically from the example in the docs. Nothing is getting written to the log file.

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
1 Answers

The FileHandler flushes to disk every 30 seconds. If you wait 30 seconds you'll see that data is being written.

From the documentation:

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.

Related