From c9246bb392da353f4fbdf2e5dbef4ef321341e4e Mon Sep 17 00:00:00 2001 From: Manason Date: Thu, 21 Sep 2023 23:39:00 -0700 Subject: [PATCH] feat: added lib.print to print different log levels to console (#425) Co-authored-by: Linden <65407488+thelindat@users.noreply.github.com> --- imports/print/shared.lua | 47 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 imports/print/shared.lua diff --git a/imports/print/shared.lua b/imports/print/shared.lua new file mode 100644 index 0000000..a067dd1 --- /dev/null +++ b/imports/print/shared.lua @@ -0,0 +1,47 @@ +---@enum PrintLevel +local printLevel = { + error = 1, + warn = 2, + info = 3, + verbose = 4, + debug = 5, +} + +local levelPrefixes = { + '^1[ERROR]', + '^3[WARN]', + '^7[INFO]', + '^4[VERBOSE]', + '^6[DEBUG]', +} + +local resourcePrintLevel = printLevel[GetConvar('ox:printlevel:' .. cache.resource, GetConvar('ox:printlevel', 'info'))] +local template = ('^5[%s] %%s %%s^7'):format(cache.resource) +local jsonOptions = { sort_keys = true, indent = true } + +---Prints to console conditionally based on what ox:printlevel is. +---Any print with a level more severe will also print. If ox:printlevel is info, then warn and error prints will appear as well, but debug prints will not. +---@param level PrintLevel +---@param ... any +local function libPrint(level, ...) + if level > resourcePrintLevel then return end + + local args = { ... } + + for i = 1, #args do + local arg = args[i] + args[i] = type(arg) == 'table' and json.encode(arg, jsonOptions) or tostring(arg) + end + + print(template:format(levelPrefixes[level], table.concat(args, '\t'))) +end + +lib.print = { + error = function(...) libPrint(printLevel.error, ...) end, + warn = function(...) libPrint(printLevel.warn, ...) end, + info = function(...) libPrint(printLevel.info, ...) end, + verbose = function(...) libPrint(printLevel.verbose, ...) end, + debug = function(...) libPrint(printLevel.debug, ...) end, +} + +return lib.print