chrome_net_log.cc revision eb525c5499e34cc9c4b825d6d9e75bb07cc06ace
1// Copyright (c) 2012 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#include "chrome/browser/net/chrome_net_log.h"
6
7#include <stdio.h>
8
9#include "base/command_line.h"
10#include "base/logging.h"
11#include "base/strings/string_number_conversions.h"
12#include "base/strings/string_util.h"
13#include "base/values.h"
14#include "chrome/browser/net/net_log_temp_file.h"
15#include "chrome/browser/ui/webui/net_internals/net_internals_ui.h"
16#include "chrome/common/chrome_switches.h"
17#include "content/public/common/content_switches.h"
18#include "net/base/net_log_logger.h"
19
20ChromeNetLog::ChromeNetLog()
21    : net_log_temp_file_(new NetLogTempFile(this)) {
22  const CommandLine* command_line = CommandLine::ForCurrentProcess();
23  // Adjust base log level based on command line switch, if present.
24  // This is done before adding any observers so the call to UpdateLogLevel when
25  // an observers is added will set |effective_log_level_| correctly.
26  if (command_line->HasSwitch(switches::kNetLogLevel)) {
27    std::string log_level_string =
28        command_line->GetSwitchValueASCII(switches::kNetLogLevel);
29    int command_line_log_level;
30    if (base::StringToInt(log_level_string, &command_line_log_level) &&
31        command_line_log_level >= LOG_ALL &&
32        command_line_log_level <= LOG_NONE) {
33      SetBaseLogLevel(static_cast<LogLevel>(command_line_log_level));
34    }
35  }
36
37  if (command_line->HasSwitch(switches::kLogNetLog)) {
38    base::FilePath log_path =
39        command_line->GetSwitchValuePath(switches::kLogNetLog);
40    // Much like logging.h, bypass threading restrictions by using fopen
41    // directly.  Have to write on a thread that's shutdown to handle events on
42    // shutdown properly, and posting events to another thread as they occur
43    // would result in an unbounded buffer size, so not much can be gained by
44    // doing this on another thread.  It's only used when debugging Chrome, so
45    // performance is not a big concern.
46    FILE* file = NULL;
47#if defined(OS_WIN)
48    file = _wfopen(log_path.value().c_str(), L"w");
49#elif defined(OS_POSIX)
50    file = fopen(log_path.value().c_str(), "w");
51#endif
52
53    if (file == NULL) {
54      LOG(ERROR) << "Could not open file " << log_path.value()
55                 << " for net logging";
56    } else {
57      scoped_ptr<base::Value> constants(NetInternalsUI::GetConstants());
58      net_log_logger_.reset(new net::NetLogLogger(file, *constants));
59      net_log_logger_->StartObserving(this);
60    }
61  }
62}
63
64ChromeNetLog::~ChromeNetLog() {
65  net_log_temp_file_.reset();
66  // Remove the observers we own before we're destroyed.
67  if (net_log_logger_)
68    RemoveThreadSafeObserver(net_log_logger_.get());
69}
70
71