electron/brightray/browser/net_log.cc

88 lines
2.4 KiB
C++
Raw Normal View History

2015-06-05 14:54:38 +00:00
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#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 "content/public/common/content_switches.h"
#include "net/log/net_log_util.h"
#include "net/url_request/url_request_context.h"
2015-06-06 09:03:07 +00:00
namespace {
2015-06-09 01:51:38 +00:00
scoped_ptr<base::DictionaryValue> GetConstants() {
2015-06-06 09:03:07 +00:00
scoped_ptr<base::DictionaryValue> constants = net::GetNetConstants();
// Adding client information to constants dictionary.
base::DictionaryValue* client_info = new base::DictionaryValue();
2015-06-09 01:51:38 +00:00
client_info->SetString(
"command_line",
2015-06-06 09:03:07 +00:00
base::CommandLine::ForCurrentProcess()->GetCommandLineString());
constants->Set("clientInfo", client_info);
2015-06-09 01:51:38 +00:00
return constants;
2015-06-06 09:03:07 +00:00
}
} // namespace
2015-06-05 14:54:38 +00:00
namespace brightray {
NetLog::NetLog(net::URLRequestContext* context)
: added_events_(false),
context_(context) {
auto command_line = base::CommandLine::ForCurrentProcess();
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 {
2015-06-05 18:43:10 +00:00
std::string json;
2015-06-09 01:51:38 +00:00
scoped_ptr<base::Value> constants(GetConstants().Pass());
2015-06-08 14:26:48 +00:00
base::JSONWriter::Write(constants.get(), &json);
2015-06-05 18:43:10 +00:00
fprintf(log_file_.get(), "{\"constants\": %s, \n", json.c_str());
fprintf(log_file_.get(), "\"events\": [\n");
2015-06-05 14:54:38 +00:00
2015-06-06 09:03:07 +00:00
if (context_) {
2015-06-05 14:54:38 +00:00
DCHECK(context_->CalledOnValidThread());
std::set<net::URLRequestContext*> contexts;
2015-06-06 09:03:07 +00:00
contexts.insert(context_);
2015-06-05 14:54:38 +00:00
net::CreateNetLogEntriesForActiveObjects(contexts, this);
}
DeprecatedAddObserver(this, net::NetLog::LogLevel::LOG_STRIP_PRIVATE_DATA);
}
}
NetLog::~NetLog() {
DeprecatedRemoveObserver(this);
2015-06-06 09:03:07 +00:00
// Ending events array.
2015-06-05 14:54:38 +00:00
fprintf(log_file_.get(), "]}");
log_file_.reset();
}
void NetLog::OnAddEntry(const net::NetLog::Entry& entry) {
std::string json;
base::JSONWriter::Write(entry.ToValue(), &json);
fprintf(log_file_.get(), "%s%s", (added_events_ ? ",\n" : ""), json.c_str());
added_events_ = true;
}
} // namespace brightray