Store NetLog in BrowserClient

This commit is contained in:
Cheng Zhao 2015-08-11 18:29:55 +08:00
parent edda9d0488
commit 8a92ef34a7
8 changed files with 46 additions and 79 deletions

View file

@ -4,15 +4,13 @@
#include "browser/net_log.h"
#include "browser/browser_context.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/files/file_path.h"
#include "base/values.h"
#include "content/public/common/content_switches.h"
#include "net/log/net_log_util.h"
#include "net/log/net_log_capture_mode.h"
#include "net/url_request/url_request_context.h"
namespace brightray {
namespace {
@ -31,62 +29,34 @@ scoped_ptr<base::DictionaryValue> GetConstants() {
} // namespace
namespace brightray {
NetLog::NetLog(net::URLRequestContext* context)
: added_events_(false),
context_(context) {
NetLog::NetLog() {
auto command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kLogNetLog)) {
base::FilePath log_path =
command_line->GetSwitchValuePath(switches::kLogNetLog);
if (!command_line->HasSwitch(switches::kLogNetLog))
return;
#if defined(OS_WIN)
log_file_.reset(_wfopen(log_path.value().c_str(), L"w"));
#elif defined(OS_POSIX)
log_file_.reset(fopen(log_path.value().c_str(), "w"));
#endif
base::FilePath log_path = command_line->GetSwitchValuePath(switches::kLogNetLog);
#if defined(OS_WIN)
log_file_.reset(_wfopen(log_path.value().c_str(), L"w"));
#elif defined(OS_POSIX)
log_file_.reset(fopen(log_path.value().c_str(), "w"));
#endif
if (!log_file_) {
LOG(ERROR) << "Could not open file: " << log_path.value()
<< "for net logging";
} else {
std::string json;
scoped_ptr<base::Value> constants(GetConstants().Pass());
base::JSONWriter::Write(constants.get(), &json);
fprintf(log_file_.get(), "{\"constants\": %s, \n", json.c_str());
fprintf(log_file_.get(), "\"events\": [\n");
if (context_) {
DCHECK(context_->CalledOnValidThread());
std::set<net::URLRequestContext*> contexts;
contexts.insert(context_);
net::CreateNetLogEntriesForActiveObjects(contexts, this);
}
DeprecatedAddObserver(this, net::NetLogCaptureMode::Default());
}
if (!log_file_) {
LOG(ERROR) << "Could not open file: " << log_path.value()
<< "for net logging";
return;
}
}
NetLog::~NetLog() {
if (log_file_) {
DeprecatedRemoveObserver(this);
// Ending events array.
fprintf(log_file_.get(), "]}");
log_file_.reset();
}
}
void NetLog::OnAddEntry(const net::NetLog::Entry& entry) {
std::string json;
base::JSONWriter::Write(entry.ToValue(), &json);
void NetLog::StartLogging(net::URLRequestContext* url_request_context) {
if (!log_file_)
return;
fprintf(log_file_.get(), "%s%s", (added_events_ ? ",\n" : ""), json.c_str());
added_events_ = true;
scoped_ptr<base::Value> constants(GetConstants());
write_to_file_observer_.StartObserving(this, log_file_.Pass(), constants.get(), url_request_context);
}
} // namespace brightray