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_
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"
21 #include "net/log/net_log_capture_mode.h"
24 class DictionaryValue
;
30 // NetLog is the destination for log messages generated by the network stack.
31 // Each log message has a "source" field which identifies the specific entity
32 // that generated the message (for example, which URLRequest or which
35 // To avoid needing to pass in the "source ID" to the logging functions, NetLog
36 // is usually accessed through a BoundNetLog, which will always pass in a
37 // specific source ID.
39 // All methods are thread safe, with the exception that no NetLog or
40 // NetLog::ThreadSafeObserver functions may be called by an observer's
41 // OnAddEntry() method. Doing so will result in a deadlock.
43 // For a broader introduction see the design document:
44 // https://sites.google.com/a/chromium.org/dev/developers/design-documents/network-stack/netlog
45 class NET_EXPORT NetLog
{
48 #define EVENT_TYPE(label) TYPE_##label,
49 #include "net/log/net_log_event_type_list.h"
54 // The 'phase' of an event trace (whether it marks the beginning or end
62 // The "source" identifies the entity that generated the log message.
64 #define SOURCE_TYPE(label) SOURCE_##label,
65 #include "net/log/net_log_source_type_list.h"
70 // A callback function that return a Value representation of the parameters
71 // associated with an event. If called, it will be called synchonously,
72 // so it need not have owning references. May be called more than once, or
73 // not at all. May return NULL.
74 typedef base::Callback
<base::Value
*(NetLogCaptureMode
)> ParametersCallback
;
76 // Identifies the entity that generated this log. The |id| field should
77 // uniquely identify the source, and is used by log observers to infer
78 // message groupings. Can use NetLog::NextID() to create unique IDs.
79 struct NET_EXPORT Source
{
80 static const uint32 kInvalidId
;
83 Source(SourceType type
, uint32 id
);
86 // Adds the source to a DictionaryValue containing event parameters,
87 // using the name "source_dependency".
88 void AddToEventParameters(base::DictionaryValue
* event_params
) const;
90 // Returns a callback that returns a dictionary with a single entry
91 // named "source_dependecy" that describes |this|.
92 ParametersCallback
ToEventParametersCallback() const;
94 // Attempts to extract a Source from a set of event parameters. Returns
95 // true and writes the result to |source| on success. Returns false and
96 // makes |source| an invalid source on failure.
97 // TODO(mmenke): Long term, we want to remove this.
98 static bool FromEventParameters(base::Value
* event_params
, Source
* source
);
104 struct NET_EXPORT EntryData
{
105 EntryData(EventType type
,
108 base::TimeTicks time
,
109 const ParametersCallback
* parameters_callback
);
112 const EventType type
;
114 const EventPhase phase
;
115 const base::TimeTicks time
;
116 const ParametersCallback
* const parameters_callback
;
119 // An Entry pre-binds EntryData to a capture mode, so observers will observe
120 // the output of ToValue() and ParametersToValue() at their log capture mode
121 // rather than the current maximum.
122 class NET_EXPORT Entry
{
124 Entry(const EntryData
* data
, NetLogCaptureMode capture_mode
);
127 EventType
type() const { return data_
->type
; }
128 Source
source() const { return data_
->source
; }
129 EventPhase
phase() const { return data_
->phase
; }
131 // Serializes the specified event to a Value. The Value also includes the
132 // current time. Caller takes ownership of returned Value. Takes in a time
133 // to allow back-dating entries.
134 base::Value
* ToValue() const;
136 // Returns the parameters as a Value. Returns NULL if there are no
137 // parameters. Caller takes ownership of returned Value.
138 base::Value
* ParametersToValue() const;
141 const EntryData
* const data_
;
143 // Log capture mode when the event occurred.
144 const NetLogCaptureMode capture_mode_
;
146 // It is not safe to copy this class, since |parameters_callback_| may
147 // include pointers that become stale immediately after the event is added,
148 // even if the code were modified to keep its own copy of the callback.
149 DISALLOW_COPY_AND_ASSIGN(Entry
);
152 // An observer, that must ensure its own thread safety, for events
153 // being added to a NetLog.
154 class NET_EXPORT ThreadSafeObserver
{
156 // Constructs an observer that wants to see network events, with
157 // the specified minimum event granularity. A ThreadSafeObserver can only
158 // observe a single NetLog at a time.
160 // Observers will be called on the same thread an entry is added on,
161 // and are responsible for ensuring their own thread safety.
163 // Observers must stop watching a NetLog before either the Observer or the
164 // NetLog is destroyed.
165 ThreadSafeObserver();
167 // Returns the capture mode for events this observer wants to
168 // receive. Must not be called when not watching a NetLog.
169 NetLogCaptureMode
capture_mode() const;
171 // Returns the NetLog we are currently watching, if any. Returns NULL
173 NetLog
* net_log() const;
175 // This method will be called on the thread that the event occurs on. It
176 // is the responsibility of the observer to handle it in a thread safe
179 // It is illegal for an Observer to call any NetLog or
180 // NetLog::Observer functions in response to a call to OnAddEntry.
181 virtual void OnAddEntry(const Entry
& entry
) = 0;
184 virtual ~ThreadSafeObserver();
189 void OnAddEntryData(const EntryData
& entry_data
);
191 // Both of these values are only modified by the NetLog.
192 NetLogCaptureMode capture_mode_
;
195 DISALLOW_COPY_AND_ASSIGN(ThreadSafeObserver
);
201 // Emits a global event to the log stream, with its own unique source ID.
202 void AddGlobalEntry(EventType type
);
203 void AddGlobalEntry(EventType type
,
204 const NetLog::ParametersCallback
& parameters_callback
);
206 // Returns a unique ID which can be used as a source ID. All returned IDs
207 // will be unique and greater than 0.
210 // Returns the capture mode for this NetLog. This is used to avoid computing
211 // and saving expensive log entries.
212 NetLogCaptureMode
GetCaptureMode() const;
214 // Adds an observer and sets its log capture mode. The observer must not be
215 // watching any NetLog, including this one, when this is called.
217 // NetLog implementations must call NetLog::OnAddObserver to update the
218 // observer's internal state.
220 // DEPRECATED: The ability to watch the netlog stream is being phased out
221 // (crbug.com/472693) as it can be misused in production code. Please consult
222 // with a net/log OWNER before introducing a new dependency on this.
223 void DeprecatedAddObserver(ThreadSafeObserver
* observer
,
224 NetLogCaptureMode capture_mode
);
226 // Sets the log capture mode of |observer| to |capture_mode|. |observer| must
227 // be watching |this|. NetLog implementations must call
228 // NetLog::OnSetObserverCaptureMode to update the observer's internal state.
229 void SetObserverCaptureMode(ThreadSafeObserver
* observer
,
230 NetLogCaptureMode capture_mode
);
232 // Removes an observer. NetLog implementations must call
233 // NetLog::OnAddObserver to update the observer's internal state.
235 // For thread safety reasons, it is recommended that this not be called in
236 // an object's destructor.
238 // DEPRECATED: The ability to watch the netlog stream is being phased out
239 // (crbug.com/472693) as it can be misused in production code. Please consult
240 // with a net/log OWNER before introducing a new dependency on this.
241 void DeprecatedRemoveObserver(ThreadSafeObserver
* observer
);
243 // Converts a time to the string format that the NetLog uses to represent
244 // times. Strings are used since integers may overflow.
245 static std::string
TickCountToString(const base::TimeTicks
& time
);
247 // Returns a C-String symbolic name for |event_type|.
248 static const char* EventTypeToString(EventType event_type
);
250 // Returns a dictionary that maps event type symbolic names to their enum
251 // values. Caller takes ownership of the returned Value.
252 static base::Value
* GetEventTypesAsValue();
254 // Returns a C-String symbolic name for |source_type|.
255 static const char* SourceTypeToString(SourceType source_type
);
257 // Returns a dictionary that maps source type symbolic names to their enum
258 // values. Caller takes ownership of the returned Value.
259 static base::Value
* GetSourceTypesAsValue();
261 // Returns a C-String symbolic name for |event_phase|.
262 static const char* EventPhaseToString(EventPhase event_phase
);
264 // Creates a ParametersCallback that encapsulates a single bool.
265 // Warning: |name| must remain valid for the life of the callback.
266 static ParametersCallback
BoolCallback(const char* name
, bool value
);
268 // Warning: |name| must remain valid for the life of the callback.
269 // TODO(mmenke): Rename this to be consistent with Int64Callback.
270 static ParametersCallback
IntegerCallback(const char* name
, int value
);
272 // Creates a ParametersCallback that encapsulates a single int64. The
273 // callback will return the value as a StringValue, since IntegerValues
274 // only support 32-bit values.
275 // Warning: |name| must remain valid for the life of the callback.
276 static ParametersCallback
Int64Callback(const char* name
, int64 value
);
278 // Creates a ParametersCallback that encapsulates a single UTF8 string. Takes
279 // |value| as a pointer to avoid copying, and emphasize it must be valid for
280 // the life of the callback. |value| may not be NULL.
281 // Warning: |name| and |value| must remain valid for the life of the callback.
282 static ParametersCallback
StringCallback(const char* name
,
283 const std::string
* value
);
285 // Same as above, but takes in a UTF16 string.
286 static ParametersCallback
StringCallback(const char* name
,
287 const base::string16
* value
);
290 friend class BoundNetLog
;
292 void AddEntry(EventType type
,
293 const Source
& source
,
295 const NetLog::ParametersCallback
* parameters_callback
);
297 // Called whenever an observer is added or removed, or has its log
298 // capture mode changed. Must have acquired |lock_| prior to calling.
299 void UpdateCaptureMode();
301 // |lock_| protects access to |observers_|.
304 // Last assigned source ID. Incremented to get the next one.
305 base::subtle::Atomic32 last_id_
;
307 // The current capture mode. Note that the capture mode is stored as an
308 // integer rather than a NetLogCaptureMode so that it can be easily
309 // read/written without a lock using Atomic32.
310 base::subtle::Atomic32 effective_capture_mode_int32_
;
312 // |lock_| must be acquired whenever reading or writing to this.
313 ObserverList
<ThreadSafeObserver
, true> observers_
;
315 DISALLOW_COPY_AND_ASSIGN(NetLog
);
318 // Helper that binds a Source to a NetLog, and exposes convenience methods to
319 // output log messages without needing to pass in the source.
320 class NET_EXPORT BoundNetLog
{
322 BoundNetLog() : net_log_(NULL
) {}
325 // Add a log entry to the NetLog for the bound source.
326 void AddEntry(NetLog::EventType type
, NetLog::EventPhase phase
) const;
327 void AddEntry(NetLog::EventType type
,
328 NetLog::EventPhase phase
,
329 const NetLog::ParametersCallback
& get_parameters
) const;
331 // Convenience methods that call AddEntry with a fixed "capture phase"
332 // (begin, end, or none).
333 void BeginEvent(NetLog::EventType type
) const;
334 void BeginEvent(NetLog::EventType type
,
335 const NetLog::ParametersCallback
& get_parameters
) const;
337 void EndEvent(NetLog::EventType type
) const;
338 void EndEvent(NetLog::EventType type
,
339 const NetLog::ParametersCallback
& get_parameters
) const;
341 void AddEvent(NetLog::EventType type
) const;
342 void AddEvent(NetLog::EventType type
,
343 const NetLog::ParametersCallback
& get_parameters
) const;
345 // Just like AddEvent, except |net_error| is a net error code. A parameter
346 // called "net_error" with the indicated value will be recorded for the event.
347 // |net_error| must be negative, and not ERR_IO_PENDING, as it's not a true
349 void AddEventWithNetErrorCode(NetLog::EventType event_type
,
350 int net_error
) const;
352 // Just like EndEvent, except |net_error| is a net error code. If it's
353 // negative, a parameter called "net_error" with a value of |net_error| is
354 // associated with the event. Otherwise, the end event has no parameters.
355 // |net_error| must not be ERR_IO_PENDING, as it's not a true error.
356 void EndEventWithNetErrorCode(NetLog::EventType event_type
,
357 int net_error
) const;
359 // Logs a byte transfer event to the NetLog. Determines whether to log the
360 // received bytes or not based on the current logging level.
361 void AddByteTransferEvent(NetLog::EventType event_type
,
363 const char* bytes
) const;
365 NetLogCaptureMode
GetCaptureMode() const;
367 // Helper to create a BoundNetLog given a NetLog and a SourceType. Takes care
368 // of creating a unique source ID, and handles the case of NULL net_log.
369 static BoundNetLog
Make(NetLog
* net_log
, NetLog::SourceType source_type
);
371 const NetLog::Source
& source() const { return source_
; }
372 NetLog
* net_log() const { return net_log_
; }
375 // TODO(eroman): Temporary until crbug.com/467797 is solved.
381 BoundNetLog(const NetLog::Source
& source
, NetLog
* net_log
)
382 : source_(source
), net_log_(net_log
) {}
384 // TODO(eroman): Temporary until crbug.com/467797 is solved.
385 void CrashIfInvalid() const;
387 NetLog::Source source_
;
390 // TODO(eroman): Temporary until crbug.com/467797 is solved.
391 Liveness liveness_
= ALIVE
;
396 #endif // NET_LOG_NET_LOG_H_