跳转至

结构化日志


概述

演示结构化日志保存,每条日志10个字节。


代码


//每条记录包含ts, height, temperature三个属性,在字节流中占4+2+4=10个字节
var st = ["ts", "4b", "height", "2b", "temperature", "fb"];

function addLog(data)
{
    var d = Bytes.create(10);
    d.setv(st, data);

    //以日期的日作为文件名
    var date = Date.create(data.ts);
    var f = File.open(date.day.toFixed());
    File.seek(f, File.len(f));
    File.write(f, d);
    File.close(f);
}

function getLog(day, i)
{
    var ret = {};
    var f = File.open(day.toFixed());
    if(File.len(f) >= (i + 1) * 10)
    {
        File.seek(f, i * 10);
        var d = File.read(f, 10);
        ret = d.getv(st);
    }
    File.close(f);
    return ret;
}

//测试
var ts = Date.create().timestamp;
for(var i = 0; i < 100; i++)
{
    var obj = {ts : ts, height: (Math.round(Math.random() * 50)), temperature : Math.random() * 50};
    addLog(obj);
    ts += 12 * 60 * 60; //时间增加12小时
}
for(var i = 1; i <= 10; i++)
{
    var data = getLog(i, 0);
    print(Date.create(data.ts).format("%Y-%0M-%0D %0h:%0m:%0s"), data.height, data.temperature);
}

下载代码(右键另存为):log.js