cocos2d-lua:将打印的Lua日志写入本地文件

写入文件

自定义一个打印Log的函数,在调用这个函数进行Log打印的时候,会调用io.writefile使用追加的方式将Log信息写入到本地文件中!

-- 将日志信息写入文件中
function writeLog2File(msg)
	if cc.Application:getInstance():getTargetPlatform() == cc.PLATFORM_OS_WINDOWS then  -- win
		local logFilePath = cc.FileUtils:getInstance():getWritablePath() .. "debug_log.txt"
		-- functions.lua中的io.writefile,见附录Ⅰ
		io.writefile(logFilePath , string.format("%s: %s\n", os.date(), msg), "a+")  -- "a+":追加
	end
end

-- 自定义print
function printLog(msg, ...)
	msg = msg .. " "
	local args = {...}
	for _, arg in pairs(args) do
		msg = msg .. tostring(arg) .. " "
	end
	print(msg) -- CCLuaStack.cpp中的lua_print,见附录Ⅱ

	writeLog2File(msg)
end

删除文件

在应用启动或者其他合适的时候删除本地日志文件,控制日志文件的生命周期,否则会一直追加新的Log信息!

-- 删除本地文件
function deleteLogFile()
    if cc.Application:getInstance():getTargetPlatform() ~= cc.PLATFORM_OS_WINDOWS then return end
    local logFilePath = cc.FileUtils:getInstance():getWritablePath() .. "debug_log.txt"
	local isExist = cc.FileUtils:getInstance():isFileExist(logFilePath)
	if isExist then
        cc.FileUtils:getInstance():removeFile(logFilePath)
    end
end

附录Ⅰ

--[[
	io操作:将内容写入文件
	@param path 目标文件路径,文件不存在会自动创建
	@param content 写入的内容
	@param mode 写入的模式
	@return 写入结果
]]

function io.writefile(path, content, mode)
    mode = mode or "w+b"
    local file = io.open(path, mode)
    if file then
        if file:write(content) == nil then return false end
        io.close(file)
        return true
    else
        return false
    end
end

附录Ⅱ

int lua_print(lua_State * luastate)
{
    int nargs = lua_gettop(luastate);  // lua_gettop:返回栈顶元素的索引(即栈长度)

    std::string t;
    for (int i=1; i <= nargs; i++)
    {
        if (lua_istable(luastate, i))
            t += "table";
        else if (lua_isnone(luastate, i))
            t += "none";
        else if (lua_isnil(luastate, i))
            t += "nil";
        else if (lua_isboolean(luastate, i))
        {
            if (lua_toboolean(luastate, i) != 0)
                t += "true";
            else
                t += "false";
        }
        else if (lua_isfunction(luastate, i))
            t += "function";
        else if (lua_islightuserdata(luastate, i))
            t += "lightuserdata";
        else if (lua_isthread(luastate, i))
            t += "thread";
        else
        {
            const char * str = lua_tostring(luastate, i);
            if (str)
                t += lua_tostring(luastate, i);
            else
                t += lua_typename(luastate, lua_type(luastate, i));
        }
        if (i!=nargs)
            t += "\t";
    }
    CCLOG("[LUA-print] %s", t.c_str());

    return 0;
}

Just Mark!

你可能感兴趣的:(Cocos2d)