aboutsummaryrefslogtreecommitdiffstats
path: root/vespalib/src/vespa/vespalib/trace/trace.cpp
blob: 91480a58dba682af89ca0e7f13d4ccc2964ce8a5 (plain) (blame)
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
55
56
57
58
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/vespalib/trace/trace.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <sys/time.h>

namespace vespalib {

Trace::Trace(const Trace &rhs)
    : _root(),
      _level(rhs._level)
{
    if (!rhs.isEmpty()) {
        _root = std::make_unique<TraceNode>(rhs.getRoot());
    }
}

bool
Trace::trace(uint32_t level, const string &note, bool addTime)
{
    if (!shouldTrace(level)) {
        return false;
    }
    if (addTime) {
        struct timeval tv;
        gettimeofday(&tv, nullptr);
        ensureRoot().addChild(make_string("[%ld.%06ld] %s", tv.tv_sec, static_cast<long>(tv.tv_usec), note.c_str()));
    } else {
        ensureRoot().addChild(note);
    }
    return true;
}

string
Trace::toString(size_t limit) const {
    return _root ? _root->toString(limit) : "";
}

string
Trace::encode() const {
    return isEmpty() ? "" : getRoot().encode();
}

void
Trace::clear() {
    _level = 0;
    _root.reset();
}

TraceNode &
Trace::ensureRoot() {
    if (!_root) {
        _root = std::make_unique<TraceNode>();
    }
    return *_root;
}

} // namespace vespalib