We started redesigning GpuMemoryBuffer interface to handle multiple buffers [0].
[chromium-blink-merge.git] / net / log / net_log.h
blobdd22d5ee2c3e5cdaa8beb39429bdd326d20ee36c
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.
5 #ifndef NET_LOG_NET_LOG_H_
6 #define NET_LOG_NET_LOG_H_
8 #include <string>
10 #include "build/build_config.h"
12 #include "base/atomicops.h"
13 #include "base/basictypes.h"
14 #include "base/callback_forward.h"
15 #include "base/compiler_specific.h"
16 #include "base/observer_list.h"
17 #include "base/strings/string16.h"
18 #include "base/synchronization/lock.h"
19 #include "base/time/time.h"
20 #include "net/base/net_export.h"
22 namespace base {
23 class DictionaryValue;
24 class Value;
27 namespace net {
29 // NetLog is the destination for log messages generated by the network stack.
30 // Each log message has a "source" field which identifies the specific entity
31 // that generated the message (for example, which URLRequest or which
32 // SpdySession).
34 // To avoid needing to pass in the "source ID" to the logging functions, NetLog
35 // is usually accessed through a BoundNetLog, which will always pass in a
36 // specific source ID.
38 // All methods are thread safe, with the exception that no NetLog or
39 // NetLog::ThreadSafeObserver functions may be called by an observer's
40 // OnAddEntry() method. Doing so will result in a deadlock.
42 // For a broader introduction see the design document:
43 // https://sites.google.com/a/chromium.org/dev/developers/design-documents/network-stack/netlog
44 class NET_EXPORT NetLog {
45 public:
46 enum EventType {
47 #define EVENT_TYPE(label) TYPE_##label,
48 #include "net/log/net_log_event_type_list.h"
49 #undef EVENT_TYPE
50 EVENT_COUNT
53 // The 'phase' of an event trace (whether it marks the beginning or end
54 // of an event.).
55 enum EventPhase {
56 PHASE_NONE,
57 PHASE_BEGIN,
58 PHASE_END,
61 // The "source" identifies the entity that generated the log message.
62 enum SourceType {
63 #define SOURCE_TYPE(label) SOURCE_##label,
64 #include "net/log/net_log_source_type_list.h"
65 #undef SOURCE_TYPE
66 SOURCE_COUNT
69 // Specifies the granularity of events that should be emitted to the log.
71 // Since the LogLevel may be read and set on any thread without locking, it
72 // may be possible for an Observer to receive an event or parameters that
73 // normally wouldn't be logged at the currently active log level.
74 enum LogLevel {
75 // Log everything possible, even if it is slow and memory expensive.
76 // Includes logging of transferred bytes.
77 LOG_ALL,
79 // Log all events, but do not include the actual transferred bytes as
80 // parameters for bytes sent/received events.
81 LOG_ALL_BUT_BYTES,
83 // Log all events, but do not include the actual transferred bytes and
84 // remove cookies and HTTP credentials.
85 LOG_STRIP_PRIVATE_DATA,
87 // Don't log any events.
88 LOG_NONE,
91 // A callback function that return a Value representation of the parameters
92 // associated with an event. If called, it will be called synchonously,
93 // so it need not have owning references. May be called more than once, or
94 // not at all. May return NULL.
95 typedef base::Callback<base::Value*(LogLevel)> ParametersCallback;
97 // Identifies the entity that generated this log. The |id| field should
98 // uniquely identify the source, and is used by log observers to infer
99 // message groupings. Can use NetLog::NextID() to create unique IDs.
100 struct NET_EXPORT Source {
101 static const uint32 kInvalidId;
103 Source();
104 Source(SourceType type, uint32 id);
105 bool IsValid() const;
107 // Adds the source to a DictionaryValue containing event parameters,
108 // using the name "source_dependency".
109 void AddToEventParameters(base::DictionaryValue* event_params) const;
111 // Returns a callback that returns a dictionary with a single entry
112 // named "source_dependecy" that describes |this|.
113 ParametersCallback ToEventParametersCallback() const;
115 // Attempts to extract a Source from a set of event parameters. Returns
116 // true and writes the result to |source| on success. Returns false and
117 // makes |source| an invalid source on failure.
118 // TODO(mmenke): Long term, we want to remove this.
119 static bool FromEventParameters(base::Value* event_params, Source* source);
121 SourceType type;
122 uint32 id;
125 struct NET_EXPORT EntryData {
126 EntryData(EventType type,
127 Source source,
128 EventPhase phase,
129 base::TimeTicks time,
130 const ParametersCallback* parameters_callback);
131 ~EntryData();
133 const EventType type;
134 const Source source;
135 const EventPhase phase;
136 const base::TimeTicks time;
137 const ParametersCallback* const parameters_callback;
140 // An Entry pre-binds EntryData to a LogLevel, so observers will observe the
141 // output of ToValue() and ParametersToValue() at their log level rather than
142 // current maximum.
143 class NET_EXPORT Entry {
144 public:
145 Entry(const EntryData* data, LogLevel log_level);
146 ~Entry();
148 EventType type() const { return data_->type; }
149 Source source() const { return data_->source; }
150 EventPhase phase() const { return data_->phase; }
152 // Serializes the specified event to a Value. The Value also includes the
153 // current time. Caller takes ownership of returned Value. Takes in a time
154 // to allow back-dating entries.
155 base::Value* ToValue() const;
157 // Returns the parameters as a Value. Returns NULL if there are no
158 // parameters. Caller takes ownership of returned Value.
159 base::Value* ParametersToValue() const;
161 private:
162 const EntryData* const data_;
164 // Log level when the event occurred.
165 const LogLevel log_level_;
167 // It is not safe to copy this class, since |parameters_callback_| may
168 // include pointers that become stale immediately after the event is added,
169 // even if the code were modified to keep its own copy of the callback.
170 DISALLOW_COPY_AND_ASSIGN(Entry);
173 // An observer, that must ensure its own thread safety, for events
174 // being added to a NetLog.
175 class NET_EXPORT ThreadSafeObserver {
176 public:
177 // Constructs an observer that wants to see network events, with
178 // the specified minimum event granularity. A ThreadSafeObserver can only
179 // observe a single NetLog at a time.
181 // Observers will be called on the same thread an entry is added on,
182 // and are responsible for ensuring their own thread safety.
184 // Observers must stop watching a NetLog before either the Observer or the
185 // NetLog is destroyed.
186 ThreadSafeObserver();
188 // Returns the minimum log level for events this observer wants to
189 // receive. Must not be called when not watching a NetLog.
190 LogLevel log_level() const;
192 // Returns the NetLog we are currently watching, if any. Returns NULL
193 // otherwise.
194 NetLog* net_log() const;
196 // This method will be called on the thread that the event occurs on. It
197 // is the responsibility of the observer to handle it in a thread safe
198 // manner.
200 // It is illegal for an Observer to call any NetLog or
201 // NetLog::Observer functions in response to a call to OnAddEntry.
202 virtual void OnAddEntry(const Entry& entry) = 0;
204 protected:
205 virtual ~ThreadSafeObserver();
207 private:
208 friend class NetLog;
210 void OnAddEntryData(const EntryData& entry_data);
212 // Both of these values are only modified by the NetLog.
213 LogLevel log_level_;
214 NetLog* net_log_;
216 DISALLOW_COPY_AND_ASSIGN(ThreadSafeObserver);
219 NetLog();
220 virtual ~NetLog();
222 // Emits a global event to the log stream, with its own unique source ID.
223 void AddGlobalEntry(EventType type);
224 void AddGlobalEntry(EventType type,
225 const NetLog::ParametersCallback& parameters_callback);
227 // Returns a unique ID which can be used as a source ID. All returned IDs
228 // will be unique and greater than 0.
229 uint32 NextID();
231 // Returns the logging level for this NetLog. This is used to avoid computing
232 // and saving expensive log entries.
233 LogLevel GetLogLevel() const;
235 // Adds an observer and sets its log level. The observer must not be
236 // watching any NetLog, including this one, when this is called.
238 // NetLog implementations must call NetLog::OnAddObserver to update the
239 // observer's internal state.
241 // DEPRECATED: The ability to watch the netlog stream is being phased out
242 // (crbug.com/472693) as it can be misused in production code. Please consult
243 // with a net/log OWNER before introducing a new dependency on this.
244 void DeprecatedAddObserver(ThreadSafeObserver* observer, LogLevel log_level);
246 // Sets the log level of |observer| to |log_level|. |observer| must be
247 // watching |this|. NetLog implementations must call
248 // NetLog::OnSetObserverLogLevel to update the observer's internal state.
249 void SetObserverLogLevel(ThreadSafeObserver* observer, LogLevel log_level);
251 // Removes an observer. NetLog implementations must call
252 // NetLog::OnAddObserver to update the observer's internal state.
254 // For thread safety reasons, it is recommended that this not be called in
255 // an object's destructor.
257 // DEPRECATED: The ability to watch the netlog stream is being phased out
258 // (crbug.com/472693) as it can be misused in production code. Please consult
259 // with a net/log OWNER before introducing a new dependency on this.
260 void DeprecatedRemoveObserver(ThreadSafeObserver* observer);
262 // Converts a time to the string format that the NetLog uses to represent
263 // times. Strings are used since integers may overflow.
264 static std::string TickCountToString(const base::TimeTicks& time);
266 // Returns a C-String symbolic name for |event_type|.
267 static const char* EventTypeToString(EventType event_type);
269 // Returns a dictionary that maps event type symbolic names to their enum
270 // values. Caller takes ownership of the returned Value.
271 static base::Value* GetEventTypesAsValue();
273 // Returns a C-String symbolic name for |source_type|.
274 static const char* SourceTypeToString(SourceType source_type);
276 // Returns a dictionary that maps source type symbolic names to their enum
277 // values. Caller takes ownership of the returned Value.
278 static base::Value* GetSourceTypesAsValue();
280 // Returns a C-String symbolic name for |event_phase|.
281 static const char* EventPhaseToString(EventPhase event_phase);
283 // Returns true if |log_level| indicates the actual bytes transferred should
284 // be logged. This is only the case when |log_level| is LOG_ALL.
285 static bool IsLoggingBytes(LogLevel log_level);
287 // Returns true if |log_level| indicates that events should be logged. This is
288 // the case when |log_level| is anything other than LOG_NONE.
289 static bool IsLogging(LogLevel log_level);
291 // Creates a ParametersCallback that encapsulates a single integer.
292 // Warning: |name| must remain valid for the life of the callback.
293 // TODO(mmenke): Rename this to be consistent with Int64Callback.
294 static ParametersCallback IntegerCallback(const char* name, int value);
296 // Creates a ParametersCallback that encapsulates a single int64. The
297 // callback will return the value as a StringValue, since IntegerValues
298 // only support 32-bit values.
299 // Warning: |name| must remain valid for the life of the callback.
300 static ParametersCallback Int64Callback(const char* name, int64 value);
302 // Creates a ParametersCallback that encapsulates a single UTF8 string. Takes
303 // |value| as a pointer to avoid copying, and emphasize it must be valid for
304 // the life of the callback. |value| may not be NULL.
305 // Warning: |name| and |value| must remain valid for the life of the callback.
306 static ParametersCallback StringCallback(const char* name,
307 const std::string* value);
309 // Same as above, but takes in a UTF16 string.
310 static ParametersCallback StringCallback(const char* name,
311 const base::string16* value);
313 private:
314 friend class BoundNetLog;
316 void AddEntry(EventType type,
317 const Source& source,
318 EventPhase phase,
319 const NetLog::ParametersCallback* parameters_callback);
321 // Called whenever an observer is added or removed, or has its log level
322 // changed. Must have acquired |lock_| prior to calling.
323 void UpdateLogLevel();
325 // |lock_| protects access to |observers_|.
326 base::Lock lock_;
328 // Last assigned source ID. Incremented to get the next one.
329 base::subtle::Atomic32 last_id_;
331 // The current log level.
332 base::subtle::Atomic32 effective_log_level_;
334 // |lock_| must be acquired whenever reading or writing to this.
335 ObserverList<ThreadSafeObserver, true> observers_;
337 DISALLOW_COPY_AND_ASSIGN(NetLog);
340 // Helper that binds a Source to a NetLog, and exposes convenience methods to
341 // output log messages without needing to pass in the source.
342 class NET_EXPORT BoundNetLog {
343 public:
344 BoundNetLog() : net_log_(NULL) {}
345 ~BoundNetLog();
347 // Add a log entry to the NetLog for the bound source.
348 void AddEntry(NetLog::EventType type, NetLog::EventPhase phase) const;
349 void AddEntry(NetLog::EventType type,
350 NetLog::EventPhase phase,
351 const NetLog::ParametersCallback& get_parameters) const;
353 // Convenience methods that call AddEntry with a fixed "capture phase"
354 // (begin, end, or none).
355 void BeginEvent(NetLog::EventType type) const;
356 void BeginEvent(NetLog::EventType type,
357 const NetLog::ParametersCallback& get_parameters) const;
359 void EndEvent(NetLog::EventType type) const;
360 void EndEvent(NetLog::EventType type,
361 const NetLog::ParametersCallback& get_parameters) const;
363 void AddEvent(NetLog::EventType type) const;
364 void AddEvent(NetLog::EventType type,
365 const NetLog::ParametersCallback& get_parameters) const;
367 // Just like AddEvent, except |net_error| is a net error code. A parameter
368 // called "net_error" with the indicated value will be recorded for the event.
369 // |net_error| must be negative, and not ERR_IO_PENDING, as it's not a true
370 // error.
371 void AddEventWithNetErrorCode(NetLog::EventType event_type,
372 int net_error) const;
374 // Just like EndEvent, except |net_error| is a net error code. If it's
375 // negative, a parameter called "net_error" with a value of |net_error| is
376 // associated with the event. Otherwise, the end event has no parameters.
377 // |net_error| must not be ERR_IO_PENDING, as it's not a true error.
378 void EndEventWithNetErrorCode(NetLog::EventType event_type,
379 int net_error) const;
381 // Logs a byte transfer event to the NetLog. Determines whether to log the
382 // received bytes or not based on the current logging level.
383 void AddByteTransferEvent(NetLog::EventType event_type,
384 int byte_count,
385 const char* bytes) const;
387 NetLog::LogLevel GetLogLevel() const;
389 // Shortcut for NetLog::IsLoggingBytes(this->GetLogLevel()).
390 bool IsLoggingBytes() const;
392 // Shortcut for NetLog::IsLogging(this->GetLogLevel()).
393 bool IsLogging() const;
395 // Helper to create a BoundNetLog given a NetLog and a SourceType. Takes care
396 // of creating a unique source ID, and handles the case of NULL net_log.
397 static BoundNetLog Make(NetLog* net_log, NetLog::SourceType source_type);
399 const NetLog::Source& source() const { return source_; }
400 NetLog* net_log() const { return net_log_; }
402 private:
403 // TODO(eroman): Temporary until crbug.com/467797 is solved.
404 enum Liveness {
405 ALIVE = 0xCA11AB13,
406 DEAD = 0xDEADBEEF,
409 BoundNetLog(const NetLog::Source& source, NetLog* net_log)
410 : source_(source), net_log_(net_log) {}
412 // TODO(eroman): Temporary until crbug.com/467797 is solved.
413 void CrashIfInvalid() const;
415 NetLog::Source source_;
416 NetLog* net_log_;
418 // TODO(eroman): Temporary until crbug.com/467797 is solved.
419 Liveness liveness_ = ALIVE;
422 } // namespace net
424 #endif // NET_LOG_NET_LOG_H_