blob: 075f8d4f5f386d331603f86bf5916502dfdd2ae7 [file] [log] [blame]
Nasko Oskovae49e292020-08-13 02:08:511// Copyright 2020 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef CONTENT_COMMON_TRACE_UTILS_H_
6#define CONTENT_COMMON_TRACE_UTILS_H_
7
8#include <string>
9
10#include "base/trace_event/traced_value.h"
11
12namespace content {
13
Piotr Tworekbad51282020-09-30 19:17:5914// This can't be a struct since in C++14 static constexpr structure members
15// have external linkage. This has been fixed in C++17.
16namespace tracing_category {
17static constexpr const char kNavigation[] = "navigation";
18}
Nasko Oskovae49e292020-08-13 02:08:5119
20// Class which facilitates annotating with traces all possible return paths
21// from a function or a method. Setting the return reason is enforced by a
22// CHECK at runtime to ensure that no return branches have been missed.
23// Template usage is necessary since the tracing code requires the category to
24// be constant at compile time.
25//
26// Example usage:
27//
28// void SomeMethod() {
Piotr Tworekbad51282020-09-30 19:17:5929// TraceReturnReason<tracing_category::kNavigation> trace_return("Method");
Nasko Oskovae49e292020-08-13 02:08:5130//
31// if (condition) {
32// trace_return.set_return_reason("foo");
33// trace_return.traced_value()->SetBoolean("condition", true);
34// return;
35// }
36//
37// trace_return.set_return_reason("default return");
38// return;
39// }
40//
41template <const char* category>
42class TraceReturnReason {
43 public:
44 explicit TraceReturnReason(const char* const name)
45 : name_(name),
46 traced_value_(std::make_unique<base::trace_event::TracedValue>()) {
47 TRACE_EVENT_BEGIN0(category, name_);
48 }
49
50 ~TraceReturnReason() {
51 CHECK(reason_set_);
52 TRACE_EVENT_END1(category, name_, "return", std::move(traced_value_));
53 }
54
55 void set_return_reason(const std::string& reason) {
56 reason_set_ = true;
57 traced_value_->SetString("reason", reason);
58 }
59
60 // This method exposes the internal TracedValue member so usage of this
61 // class allows easy addition of more data to the end of the event.
62 base::trace_event::TracedValue* traced_value() { return traced_value_.get(); }
63
64 private:
65 const char* const name_;
66 bool reason_set_ = false;
67 std::unique_ptr<base::trace_event::TracedValue> traced_value_;
68};
69
70} // namespace content
71
72#endif // CONTENT_COMMON_TRACE_UTILS_H_