From 63762921e2890e5260d5d2c954a32e769f6889eb Mon Sep 17 00:00:00 2001 From: Michael Tremer Date: Wed, 22 May 2024 15:35:28 +0000 Subject: [PATCH] lua: Implement setting a log callback function Signed-off-by: Michael Tremer --- src/lua/location.c | 56 ++++++++++++++++++++++++++++++++++++++++++++++ tests/lua/main.lua | 22 ++++++++++++++++++ 2 files changed, 78 insertions(+) diff --git a/src/lua/location.c b/src/lua/location.c index b7d2c0e..1c94889 100644 --- a/src/lua/location.c +++ b/src/lua/location.c @@ -15,6 +15,7 @@ */ #include +#include #include #include @@ -33,12 +34,67 @@ struct loc_ctx* ctx = NULL; +static int log_callback_ref = 0; + +static void log_callback(struct loc_ctx* _ctx, void* data, int priority, const char* file, + int line, const char* fn, const char* format, va_list args) { + char* message = NULL; + int r; + + lua_State* L = data; + + // Format the log message + r = vasprintf(&message, format, args); + if (r < 0) + return; + + // Fetch the Lua callback function + lua_rawgeti(L, LUA_REGISTRYINDEX, log_callback_ref); + + // Pass the priority as first argument + lua_pushnumber(L, priority); + + // Pass the message as second argument + lua_pushstring(L, message); + + // Call the function + lua_call(L, 2, 0); + + free(message); +} + +static int set_log_callback(lua_State* L) { + // Check if we have received a function + luaL_checktype(L, 1, LUA_TFUNCTION); + + // Store a reference to the callback function + log_callback_ref = luaL_ref(L, LUA_REGISTRYINDEX); + + // Register our callback helper + if (ctx) + loc_set_log_callback(ctx, log_callback, L); + + return 0; +} + +static int set_log_level(lua_State* L) { + const int level = luaL_checknumber(L, 1); + + // Store the new log level + if (ctx) + loc_set_log_priority(ctx, level); + + return 0; +} + static int version(lua_State* L) { lua_pushstring(L, PACKAGE_VERSION); return 1; } static const struct luaL_Reg location_functions[] = { + { "set_log_callback", set_log_callback }, + { "set_log_level", set_log_level }, { "version", version }, { NULL, NULL }, }; diff --git a/tests/lua/main.lua b/tests/lua/main.lua index e139b2d..0133dc5 100755 --- a/tests/lua/main.lua +++ b/tests/lua/main.lua @@ -30,6 +30,28 @@ function test_load() print(location.version()) end +log_callback_called = 0 + +function log_callback(level, message) + log_callback_called = 1 + print("LOG " .. message) +end + +function test_log_callback() + location = require("location") + + -- Set the callback + location.set_log_callback(log_callback) + + -- Enable debugging + location.set_log_level(7) + + -- Perform some random operation + local db = location.Database.open(ENV_TEST_DATABASE) + + luaunit.assertIsTrue(log_callback_called) +end + function test_open_database() location = require("location") -- 2.39.5