close
Skip to main content
This release is versions behind 0.224.14 — the latest version of @std/log.
Works with
This package works with DenoIt is unknown whether this package works with Bun
This package works with Deno
It is unknown whether this package works with Bun
JSR Score88%
Downloads19,089/wk
Published2 years ago (0.212.0)

UNSTABLE: A customizable logger framework

Examples

Example 1

import * as log from "@std/log";

// Simple default logger out of the box. You can customize it
// by overriding logger and handler named "default", or providing
// additional logger configurations. You can log any data type.
log.debug("Hello world");
log.info(123456);
log.warn(true);
log.error({ foo: "bar", fizz: "bazz" });
log.critical("500 Internal server error");

// custom configuration with 2 loggers (the default and `tasks` loggers).
log.setup({
  handlers: {
    console: new log.handlers.ConsoleHandler("DEBUG"),

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

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

    tasks: {
      level: "ERROR",
      handlers: ["console"],
    },
  },
});

let logger;

// get default logger.
logger = log.getLogger();
logger.debug("fizz"); // logs to `console`, because `file` handler requires "WARNING" level.
logger.warn(41256); // logs to both `console` and `file` handlers.

// get custom logger
logger = log.getLogger("tasks");
logger.debug("fizz"); // won't get output because this logger has "ERROR" level.
logger.error({ productType: "book", value: "126.11" }); // log to `console`.

// if you try to use a logger that hasn't been configured
// you're good to go, it gets created automatically with level set to 0
// so no message is logged.
const unknownLogger = log.getLogger("mystery");
unknownLogger.info("foobar"); // no-op

Custom message format example

import * as log from "@std/log";

log.setup({
  handlers: {
    stringFmt: new log.handlers.ConsoleHandler("DEBUG", {
      formatter: (record) => `[${record.levelName}] ${record.msg}`,
    }),

    functionFmt: new log.handlers.ConsoleHandler("DEBUG", {
      formatter: (logRecord) => {
        let msg = `${logRecord.level} ${logRecord.msg}`;

        logRecord.args.forEach((arg, index) => {
          msg += `, arg${index}: ${arg}`;
        });

        return msg;
      },
    }),

    anotherFmt: new log.handlers.ConsoleHandler("DEBUG", {
      formatter: (record) => `[${record.loggerName}] - ${record.levelName} ${record.msg}`,
    }),
  },

  loggers: {
    default: {
      level: "DEBUG",
      handlers: ["stringFmt", "functionFmt"],
    },
    dataLogger: {
      level: "INFO",
      handlers: ["anotherFmt"],
    },
  },
});

// calling:
log.debug("Hello, world!", 1, "two", [3, 4, 5]);
// results in: [DEBUG] Hello, world!
// output from "stringFmt" handler.
// 10 Hello, world!, arg0: 1, arg1: two, arg3: [3, 4, 5] // output from "functionFmt" formatter.

// calling:
log.getLogger("dataLogger").error("oh no!");
// results in:
// [dataLogger] - ERROR oh no! // output from anotherFmt handler.

JSON to stdout with no color example

import * as log from "@std/log";

log.setup({
  handlers: {
    jsonStdout: new log.handlers.ConsoleHandler("DEBUG", {
      formatter: log.formatters.jsonFormatter,
      useColors: false,
    }),
  },

  loggers: {
    default: {
      level: "DEBUG",
      handlers: ["jsonStdout"],
    },
  },
});

// calling:
log.info("Hey");
// results in:
// {"level":"INFO","datetime":1702481922294,"message":"Hey"}

// calling:
log.info("Hey", { product: "nail" });
// results in:
// {"level":"INFO","datetime":1702484111115,"message":"Hey","args":{"product":"nail"}}

// calling:
log.info("Hey", 1, "two", [3, 4, 5]);
// results in:
// {"level":"INFO","datetime":1702481922294,"message":"Hey","args":[1,"two",[3,4,5]]}

Custom JSON example

import * as log from "@std/log";

log.setup({
  handlers: {
    customJsonFmt: new log.handlers.ConsoleHandler("DEBUG", {
      formatter: (record) => JSON.stringify({
        lvl: record.level,
        msg: record.msg,
        time: record.datetime.toISOString(),
        name: record.loggerName,
      }),
      useColors: false,
    }),
  },

  loggers: {
    default: {
      level: "DEBUG",
      handlers: ["customJsonFmt"],
    },
  },
});

// calling:
log.info("complete");
// results in:
// {"lvl":20,"msg":"complete","time":"2023-12-13T16:38:27.328Z","name":"default"}

Inline Logging

import * as logger from "@std/log";

const stringData: string = logger.debug("hello world");
const booleanData: boolean = logger.debug(true, 1, "abc");
const fn = (): number => {
  return 123;
};
const resolvedFunctionData: number = logger.debug(fn());
console.log(stringData); // 'hello world'
console.log(booleanData); // true
console.log(resolvedFunctionData); // 123

Lazy Log Evaluation

import * as log from "@std/log";

log.setup({
  handlers: {
    console: new log.handlers.ConsoleHandler("DEBUG"),
  },

  loggers: {
    tasks: {
      level: "ERROR",
      handlers: ["console"],
    },
  },
});

function someExpensiveFn(num: number, bool: boolean) {
  // do some expensive computation
}

// not logged, as debug < error.
const data = log.debug(() => someExpensiveFn(5, true));
console.log(data); // undefined

Classes

c
BaseHandler(
levelName: LevelName,
options?: BaseHandlerOptions
)
No documentation available
  • destroy(): void
    No documentation available
  • format(logRecord: LogRecord): string
    No documentation available
  • formatter: string | FormatterFunction
    No documentation available
  • handle(logRecord: LogRecord): void
    No documentation available
  • level: number
    No documentation available
  • levelName: LevelName
    No documentation available
  • log(_msg: string): void
    No documentation available
  • setup(): void
    No documentation available
c
ConsoleHandler(
levelName: LevelName,
options?: ConsoleHandlerOptions
)

This is the default logger. It will output color coded log messages to the console via console.log().

  • applyColors(
    msg: string,
    level: number
    ): string
    No documentation available
  • format(logRecord: LogRecord): string
    No documentation available
  • log(msg: string): void
    No documentation available
c
FileHandler(
levelName: LevelName,
options: FileHandlerOptions
)

This handler will output to a file using an optional mode (default is a, e.g. append). The file will grow indefinitely. It uses a buffer for writing to file. Logs can be manually flushed with fileHandler.flush(). Log messages with a log level greater than error are immediately flushed. Logs are also flushed on process completion.

  • _buf: Uint8Array
    No documentation available
  • _encoder: TextEncoder
    No documentation available
  • _file: Deno.FsFile | undefined
    No documentation available
  • _filename: string
    No documentation available
  • _mode: LogMode
    No documentation available
  • _openOptions: Deno.OpenOptions
    No documentation available
  • _pointer: number
    No documentation available
  • destroy(): void
    No documentation available
  • flush(): void
    No documentation available
  • handle(logRecord: LogRecord): void
    No documentation available
  • log(msg: string): void
    No documentation available
  • setup(): void
    No documentation available
c
Logger(
loggerName: string,
levelName: LevelName,
options?: LoggerOptions
)
No documentation available
  • asString(
    data: unknown,
    isProperty?
    ): string
    No documentation available
  • critical<T>(
    msg: () => T,
    ...args: unknown[]
    ): T | undefined
    No documentation available
  • debug<T>(
    msg: () => T,
    ...args: unknown[]
    ): T | undefined
    No documentation available
  • error<T>(
    msg: () => T,
    ...args: unknown[]
    ): T | undefined
    No documentation available
  • handlers: BaseHandler[]
    No documentation available
  • info<T>(
    msg: () => T,
    ...args: unknown[]
    ): T | undefined
    No documentation available
  • level(): LogLevel

    Use this to retrieve the current numeric log level.

  • levelName(): LevelName
    No documentation available
  • loggerName(): string
    No documentation available
  • warn<T>(
    msg: () => T,
    ...args: unknown[]
    ): T | undefined
    No documentation available
  • warning<T>(
    msg: () => T,
    ...args: unknown[]
    ): T | undefined
    No documentation available
c
No documentation available
  • handlers: string[]
    No documentation available
  • level: LevelName
    No documentation available
c
LogRecord(options: LogRecordOptions)

An object that encapsulates provided message and arguments as well some metadata that can be later used when formatting a message.

  • args(): unknown[]
    No documentation available
  • datetime(): Date
    No documentation available
  • level: number
    No documentation available
  • levelName: string
    No documentation available
  • loggerName: string
    No documentation available
  • msg: string
    No documentation available
c
RotatingFileHandler(
levelName: LevelName,
options: RotatingFileHandlerOptions
)

This handler extends the functionality of the FileHandler by "rotating" the log file when it reaches a certain size. maxBytes specifies the maximum size in bytes that the log file can grow to before rolling over to a new one. If the size of the new log message plus the current log file size exceeds maxBytes then a roll-over is triggered. When a roll-over occurs, before the log message is written, the log file is renamed and appended with .1. If a .1 version already existed, it would have been renamed .2 first and so on. The maximum number of log files to keep is specified by maxBackupCount. After the renames are complete the log message is written to the original, now blank, file.

  • log(msg: string): void
    No documentation available
  • No documentation available
  • setup(): void
    No documentation available

Functions

f
critical<T>(
msg: (T extends GenericFunction ? never : T) | (() => T),
...args: unknown[]
): T | undefined
2 overloads

Log with critical level, using default logger.

f
debug<T>(
msg: (T extends GenericFunction ? never : T) | (() => T),
...args: unknown[]
): T | undefined
2 overloads

Log with debug level, using default logger.

f
error<T>(
msg: (T extends GenericFunction ? never : T) | (() => T),
...args: unknown[]
): T | undefined
2 overloads

Log with error level, using default logger.

f
getLogger(name?: string): Logger

Get a logger instance. If not specified name, get the default logger.

f
info<T>(
msg: (T extends GenericFunction ? never : T) | (() => T),
...args: unknown[]
): T | undefined
2 overloads

Log with info level, using default logger.

f
setup(config: LogConfig): void

Setup logger config.

f
warn<T>(
msg: (T extends GenericFunction ? never : T) | (() => T),
...args: unknown[]
): T | undefined
2 overloads

Log with warning level, using default logger.

f
warning<T>(
msg: (T extends GenericFunction ? never : T) | (() => T),
...args: unknown[]
): T | undefined
2 overloads
No documentation available

Interfaces

I
No documentation available
  • formatter: string | FormatterFunction
    No documentation available
I
No documentation available
I
No documentation available
  • filename: string
    No documentation available
  • mode: LogMode
    No documentation available
I
No documentation available
  • handlers: { [name: string]: BaseHandler; }
    No documentation available
  • loggers: { [name: string]: LoggerConfig; }
    No documentation available
I
No documentation available
  • formatter: string | FormatterFunction
    No documentation available

Type Aliases

T
LevelName = Exclude<keyof LogLevels, number>

Union of valid log level names

T
LogLevel = LogLevels[LevelName]

Union of valid log levels

T
FormatterFunction = (logRecord: LogRecord) => string
No documentation available
T
LogMode = "a" | "w" | "x"
No documentation available

Variables

v
formatters: { jsonFormatter(logRecord: LogRecord): string; }
No documentation available
  • jsonFormatter(logRecord: LogRecord): string
    No documentation available
v
LogLevels: { NOTSET: number; DEBUG: number; INFO: number; WARNING: number; ERROR: number; CRITICAL: number; }

Use this to retrieve the numeric log level by it's associated name. Defaults to INFO.

  • CRITICAL: number
    No documentation available
  • DEBUG: number
    No documentation available
  • ERROR: number
    No documentation available
  • INFO: number
    No documentation available
  • NOTSET: number
    No documentation available
  • WARNING: number
    No documentation available
v
handlers: { BaseHandler; ConsoleHandler; WriterHandler; FileHandler; RotatingFileHandler; }

Handlers are responsible for actual output of log messages. When a handler is called by a logger, it firstly checks that LogRecord's level is not lower than level of the handler. If level check passes, handlers formats log record into string and outputs it to target.

Report package

Please provide a reason for reporting this package. We will review your report and take appropriate action.

Please review the JSR usage policy before submitting a report.