1/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2/*
3 *     Copyright 2018 Couchbase, Inc
4 *
5 *   Licensed under the Apache License, Version 2.0 (the "License");
6 *   you may not use this file except in compliance with the License.
7 *   You may obtain a copy of the License at
8 *
9 *       http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *   Unless required by applicable law or agreed to in writing, software
12 *   distributed under the License is distributed on an "AS IS" BASIS,
13 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *   See the License for the specific language governing permissions and
15 *   limitations under the License.
16 */
17
18#include <chrono>
19
20#include "phosphor.h"
21#include "trace_log.h"
22
23namespace phosphor {
24struct tracepoint_info;
25
26/**
27 * RAII-style object which captures the arguments for a scoped event.
28 *
29 * If enabled==true, saves the time of object creation; upon destruction
30 * records end time and logs an event.
31 * If !enabled; then no times are recorded and no event logged.
32 */
33template <typename T, typename U>
34struct ScopedEventGuard {
35    ScopedEventGuard(const tracepoint_info* tpi_,
36                     bool enabled_,
37                     T arg1_,
38                     U arg2_)
39        : tpi(tpi_), enabled(enabled_), arg1(arg1_), arg2(arg2_) {
40        if (enabled) {
41            start = std::chrono::steady_clock::now();
42        }
43    }
44
45    ~ScopedEventGuard() {
46        if (enabled) {
47            const auto end = std::chrono::steady_clock::now();
48            TraceLog::getInstance().logEvent(
49                    tpi, start, end - start, arg1, arg2);
50        }
51    }
52
53    const tracepoint_info* tpi;
54    const bool enabled;
55    const T arg1;
56    const U arg2;
57    std::chrono::steady_clock::time_point start;
58};
59
60} // namespace phosphor
61