How to use logging


Duktape 1.x has a built-in logging framework with a small footprint, reasonable performance, and redirectable output. In Duktape 2.x that framework was moved into an optional extra ( to avoid portability issues on exotic targets.

See for details on the features and internals of the logging framework.

You can of course use any other logging framework of your choice, e.g. console.log() provided by For low memory targets something much simpler, such as a single print() binding may be the most appropriate approach.


Basic usage example:

var val1 = 'foo';
var val2 = 123;
var val3 = new Date(123456789e3);

var logger = new Duktape.Logger();  // or new Duktape.Logger('logger name')'three values:', val1, val2, val3);

The example would print something like the following to stderr:

2014-10-17T19:26:42.141Z INF test.js: three values: foo 123 1973-11-29 23:33:09.000+02:00

Duktape.Logger (constructor)

Property Description
prototype Prototype for Logger objects.
clog Representative logger for log entries written from C code.

Called as a constructor, creates a new Logger object with a specified name (first argument). If the name is omitted, Logger will automatically assign a name based on the calling function's .fileName property. If called as a normal function, throws a TypeError.

Logger instances have the following properties:

(Tail calling might theoretically affect the automatic name assignment (i.e. when logger name argument is omitted). However, constructor calls are never converted to tail calls, so this is not a practical issue.)


Property Description
raw Output a formatted log line (buffer value), by default writes to stderr.
fmt Format a single (object) argument.
trace Write a trace level (level 0, TRC) log entry.
debug Write a debug level (level 1, DBG) log entry.
info Write an info level (level 2, INF) log entry.
warn Write a warn level (level 3, WRN) log entry.
error Write an error level (level 4, ERR) log entry.
fatal Write a fatal level (level 5, FTL) log entry.
l Default log level, initial value is 2 (info).
n Default logger name, initial value is "anon".

duk_log() C API call

void duk_log(duk_context *ctx, duk_int_t level, const char *fmt, ...);

Write a formatted log entry with the specified log level (one of DUK_LOG_xxx). The log write goes through the logging framework using the Duktape.Logger.clog logger instance.


duk_log(ctx, DUK_LOG_INFO, "received message, type: %d", (int) msg_type);

duk_log_va() C API call

void duk_log_va(duk_context *ctx, duk_int_t level, const char *fmt, va_list ap);

Like duk_log() but a vararg (va_list) variant. Example:

void my_log_info(duk_context *ctx, const char *fmt, ...) {
    va_list ap;

    va_start(ap, fmt);
    duk_log_va(ctx, DUK_LOG_INFO, fmt, ap);