]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
1 | /* |
2 | * Logging | |
3 | * | |
4 | * Current logging primitive is a sprintf-style log which is convenient | |
5 | * for most C code. Another useful primitive would be to log N arguments | |
6 | * from value stack (like the Ecmascript binding does). | |
7 | */ | |
8 | ||
9 | #include "duk_internal.h" | |
10 | ||
11 | DUK_EXTERNAL void duk_log_va(duk_context *ctx, duk_int_t level, const char *fmt, va_list ap) { | |
12 | /* stridx_logfunc[] must be static to allow initializer with old compilers like BCC */ | |
13 | static const duk_uint16_t stridx_logfunc[6] = { | |
14 | DUK_STRIDX_LC_TRACE, DUK_STRIDX_LC_DEBUG, DUK_STRIDX_LC_INFO, | |
15 | DUK_STRIDX_LC_WARN, DUK_STRIDX_LC_ERROR, DUK_STRIDX_LC_FATAL | |
16 | }; | |
17 | ||
18 | DUK_ASSERT_CTX_VALID(ctx); | |
19 | ||
20 | if (level < 0) { | |
21 | level = 0; | |
22 | } else if (level > (int) (sizeof(stridx_logfunc) / sizeof(duk_uint16_t)) - 1) { | |
23 | level = (int) (sizeof(stridx_logfunc) / sizeof(duk_uint16_t)) - 1; | |
24 | } | |
25 | ||
26 | duk_push_hobject_bidx(ctx, DUK_BIDX_LOGGER_CONSTRUCTOR); | |
27 | duk_get_prop_stridx(ctx, -1, DUK_STRIDX_CLOG); | |
28 | duk_get_prop_stridx(ctx, -1, stridx_logfunc[level]); | |
29 | duk_dup(ctx, -2); | |
30 | ||
31 | /* [ ... Logger clog logfunc clog ] */ | |
32 | ||
33 | duk_push_vsprintf(ctx, fmt, ap); | |
34 | ||
35 | /* [ ... Logger clog logfunc clog(=this) msg ] */ | |
36 | ||
37 | duk_call_method(ctx, 1 /*nargs*/); | |
38 | ||
39 | /* [ ... Logger clog res ] */ | |
40 | ||
41 | duk_pop_3(ctx); | |
42 | } | |
43 | ||
44 | DUK_EXTERNAL void duk_log(duk_context *ctx, duk_int_t level, const char *fmt, ...) { | |
45 | va_list ap; | |
46 | ||
47 | DUK_ASSERT_CTX_VALID(ctx); | |
48 | ||
49 | va_start(ap, fmt); | |
50 | duk_log_va(ctx, level, fmt, ap); | |
51 | va_end(ap); | |
52 | } |