summaryrefslogtreecommitdiff
path: root/platform/node/src/node_log.cpp
blob: 63753480700061fa690338a1cb585eac3473eff5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include "node_log.hpp"
#include "util/async_queue.hpp"

namespace node_mbgl {

struct NodeLogObserver::LogMessage {
    mbgl::EventSeverity severity;
    mbgl::Event event;
    int64_t code;
    std::string text;

    LogMessage(mbgl::EventSeverity severity_, mbgl::Event event_, int64_t code_, std::string text_)
        : severity(severity_),
        event(event_),
        code(code_),
        text(text_) {}
};

NodeLogObserver::NodeLogObserver(v8::Handle<v8::Object> target)
    : queue(new Queue(uv_default_loop(), [this](LogMessage &message) {
          NanScope();

          auto msg = NanNew<v8::Object>();
          msg->Set(NanNew("class"), NanNew(mbgl::EventClass(message.event).c_str()));
          msg->Set(NanNew("severity"), NanNew(mbgl::EventSeverityClass(message.severity).c_str()));
          if (message.code != -1) {
              msg->Set(NanNew("code"), NanNew<v8::Number>(message.code));
          }
          if (!message.text.empty()) {
              msg->Set(NanNew("text"), NanNew(message.text));
          }

          v8::Local<v8::Value> argv[] = { NanNew("message"), msg };
          auto handle = NanNew<v8::Object>(module);
          auto emit = handle->Get(NanNew("emit"))->ToObject();
          emit->CallAsFunction(handle, 2, argv);
      })) {
    NanScope();
    NanAssignPersistent(module, target);

    // Don't keep the event loop alive.
    queue->unref();
}

NodeLogObserver::~NodeLogObserver() {
    queue->stop();
}

bool NodeLogObserver::onRecord(mbgl::EventSeverity severity, mbgl::Event event, int64_t code, const std::string &text) {
    queue->send({ severity, event, code, text });
    return true;
}

}