1 // Copyright 2013 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/write_to_file_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/values.h"
15 #include "net/log/net_log_util.h"
16 #include "net/url_request/url_request_context.h"
20 WriteToFileNetLogObserver::WriteToFileNetLogObserver()
21 : log_level_(NetLog::LOG_STRIP_PRIVATE_DATA
), added_events_(false) {
24 WriteToFileNetLogObserver::~WriteToFileNetLogObserver() {
27 void WriteToFileNetLogObserver::set_log_level(net::NetLog::LogLevel log_level
) {
29 log_level_
= log_level
;
32 void WriteToFileNetLogObserver::StartObserving(
34 base::ScopedFILE file
,
35 base::Value
* constants
,
36 net::URLRequestContext
* url_request_context
) {
39 added_events_
= false;
41 // Write constants to the output file. This allows loading files that have
42 // different source and event types, as they may be added and removed
43 // between Chrome versions.
46 base::JSONWriter::Write(constants
, &json
);
48 scoped_ptr
<base::DictionaryValue
> scoped_constants(GetNetConstants());
49 base::JSONWriter::Write(scoped_constants
.get(), &json
);
51 fprintf(file_
.get(), "{\"constants\": %s,\n", json
.c_str());
53 // Start events array. It's closed in StopObserving().
54 fprintf(file_
.get(), "\"events\": [\n");
56 // Add events for in progress requests if a context is given.
57 if (url_request_context
) {
58 DCHECK(url_request_context
->CalledOnValidThread());
60 std::set
<URLRequestContext
*> contexts
;
61 contexts
.insert(url_request_context
);
62 CreateNetLogEntriesForActiveObjects(contexts
, this);
65 net_log
->DeprecatedAddObserver(this, log_level_
);
68 void WriteToFileNetLogObserver::StopObserving(
69 net::URLRequestContext
* url_request_context
) {
70 net_log()->DeprecatedRemoveObserver(this);
73 fprintf(file_
.get(), "]");
75 // Write state of the URLRequestContext when logging stopped.
76 if (url_request_context
) {
77 DCHECK(url_request_context
->CalledOnValidThread());
80 scoped_ptr
<base::DictionaryValue
> net_info
=
81 GetNetInfo(url_request_context
, NET_INFO_ALL_SOURCES
);
82 base::JSONWriter::Write(net_info
.get(), &json
);
83 fprintf(file_
.get(), ",\"tabInfo\": %s\n", json
.c_str());
85 fprintf(file_
.get(), "}");
90 void WriteToFileNetLogObserver::OnAddEntry(const net::NetLog::Entry
& entry
) {
91 // Add a comma and newline for every event but the first. Newlines are needed
92 // so can load partial log files by just ignoring the last line. For this to
93 // work, lines cannot be pretty printed.
94 scoped_ptr
<base::Value
> value(entry
.ToValue());
96 base::JSONWriter::Write(value
.get(), &json
);
97 fprintf(file_
.get(), "%s%s", (added_events_
? ",\n" : ""), json
.c_str());