1 // Copyright 2014 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.
5 #include "net/log/trace_net_log_observer.h"
11 #include "base/json/json_writer.h"
12 #include "base/logging.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/trace_event/trace_event.h"
15 #include "base/values.h"
16 #include "net/log/net_log.h"
22 // TraceLog category for NetLog events.
23 const char kNetLogTracingCategory
[] = "netlog";
25 class TracedValue
: public base::trace_event::ConvertableToTraceFormat
{
27 explicit TracedValue(scoped_ptr
<base::Value
> value
) : value_(value
.Pass()) {}
30 ~TracedValue() override
{}
32 void AppendAsTraceFormat(std::string
* out
) const override
{
35 base::JSONWriter::Write(*value_
, &tmp
);
43 scoped_ptr
<base::Value
> value_
;
48 TraceNetLogObserver::TraceNetLogObserver() : net_log_to_watch_(NULL
) {
51 TraceNetLogObserver::~TraceNetLogObserver() {
52 DCHECK(!net_log_to_watch_
);
56 void TraceNetLogObserver::OnAddEntry(const NetLog::Entry
& entry
) {
57 scoped_ptr
<base::Value
> params(entry
.ParametersToValue());
58 switch (entry
.phase()) {
59 case NetLog::PHASE_BEGIN
:
60 TRACE_EVENT_NESTABLE_ASYNC_BEGIN2(
61 kNetLogTracingCategory
, NetLog::EventTypeToString(entry
.type()),
62 entry
.source().id
, "source_type",
63 NetLog::SourceTypeToString(entry
.source().type
), "params",
64 scoped_refptr
<base::trace_event::ConvertableToTraceFormat
>(
65 new TracedValue(params
.Pass())));
67 case NetLog::PHASE_END
:
68 TRACE_EVENT_NESTABLE_ASYNC_END2(
69 kNetLogTracingCategory
, NetLog::EventTypeToString(entry
.type()),
70 entry
.source().id
, "source_type",
71 NetLog::SourceTypeToString(entry
.source().type
), "params",
72 scoped_refptr
<base::trace_event::ConvertableToTraceFormat
>(
73 new TracedValue(params
.Pass())));
75 case NetLog::PHASE_NONE
:
76 TRACE_EVENT_NESTABLE_ASYNC_INSTANT2(
77 kNetLogTracingCategory
, NetLog::EventTypeToString(entry
.type()),
78 entry
.source().id
, "source_type",
79 NetLog::SourceTypeToString(entry
.source().type
), "params",
80 scoped_refptr
<base::trace_event::ConvertableToTraceFormat
>(
81 new TracedValue(params
.Pass())));
86 void TraceNetLogObserver::WatchForTraceStart(NetLog
* netlog
) {
87 DCHECK(!net_log_to_watch_
);
89 net_log_to_watch_
= netlog
;
90 base::trace_event::TraceLog::GetInstance()->AddEnabledStateObserver(this);
93 void TraceNetLogObserver::StopWatchForTraceStart() {
94 // Should only stop if is currently watching.
95 DCHECK(net_log_to_watch_
);
96 base::trace_event::TraceLog::GetInstance()->RemoveEnabledStateObserver(this);
98 net_log()->DeprecatedRemoveObserver(this);
99 net_log_to_watch_
= NULL
;
102 void TraceNetLogObserver::OnTraceLogEnabled() {
103 net_log_to_watch_
->DeprecatedAddObserver(this, NetLogCaptureMode::Default());
106 void TraceNetLogObserver::OnTraceLogDisabled() {
108 net_log()->DeprecatedRemoveObserver(this);