From e172f568e3a04ba97cf48e20dc8ee555b4ac29dc Mon Sep 17 00:00:00 2001 From: sanine Date: Wed, 24 Aug 2022 11:14:51 -0500 Subject: add logging bindings --- src/logging/logging.c | 58 ++++++++++++++++++++++++++++++--------------------- src/logging/logging.h | 4 ++++ 2 files changed, 38 insertions(+), 24 deletions(-) (limited to 'src/logging') diff --git a/src/logging/logging.c b/src/logging/logging.c index 111d524..f7583c0 100644 --- a/src/logging/logging.c +++ b/src/logging/logging.c @@ -1,38 +1,50 @@ #include #include #include +#include #include "logging/logging.h" int _honey_log_level = HONEY_WARN; -void honey_set_log_level(int level) + +#define LUA_LOG(level) \ +int log_ ## level (lua_State *L) { \ + char *msg; \ + hs_parse_args(L, hs_str(msg)); \ + honey_log_ ## level ("%s\n", msg); \ + return 0; \ +} + + +LUA_LOG(fatal); +LUA_LOG(error); +LUA_LOG(warn); +LUA_LOG(info); +LUA_LOG(debug); +LUA_LOG(trace); + + +void setup_logging(lua_State *L, int honey_tbl) { - _honey_log_level = level; + hs_create_table(L, + hs_str_cfunc("fatal", log_fatal), + hs_str_cfunc("error", log_error), + hs_str_cfunc("warn", log_warn), + hs_str_cfunc("info", log_info), + hs_str_cfunc("debug", log_debug), + hs_str_cfunc("trace", log_trace), + ); + + lua_setfield(L, honey_tbl, "log"); } -int log_fatal(lua_State *L) + +void honey_set_log_level(int level) { - //validate arguments - int count = lua_gettop(L); - if (count == 0) { - hs_throw_error(L, "no arguments provided"); - } - if (!lua_isstring(L, 1)) { - hs_throw_error(L, "first argument must be a string"); - } - lua_getglobal(L, "string"); - if (lua_isnil(L, -1)) hs_throw_error(L, "'string' table is nil!"); - lua_getfield(L, -1, "format"); //pushed string.format (function) to the lua stack - for (int i = 1; i <= count; i++) { - lua_pushvalue(L, i); - } - lua_call(L, count, 1); - const char *str = lua_tostring(L, -1); //getting result into a string - honey_log(HONEY_FATAL, "[FATAL] %s\n", str); - lua_pop(L, 2); //cleaned up stack - return 0; + _honey_log_level = level; } + void honey_log(int level, const char *fmt, ...) { if (level > _honey_log_level) return; @@ -42,5 +54,3 @@ void honey_log(int level, const char *fmt, ...) { vfprintf(stderr, fmt, args); va_end(args); } - - diff --git a/src/logging/logging.h b/src/logging/logging.h index f829169..758d7bc 100644 --- a/src/logging/logging.h +++ b/src/logging/logging.h @@ -1,6 +1,8 @@ #ifndef HONEY_LOGGING_H #define HONEY_LOGGING_H +#include + #define HONEY_FATAL 0 #define HONEY_ERROR 1 #define HONEY_WARN 2 @@ -10,6 +12,8 @@ extern int _honey_log_level; +void setup_logging(lua_State *L, int honey_tbl); + void honey_set_log_level(int level); void honey_log(int level, const char *fmt, ...); -- cgit v1.2.1