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 #include "content/browser/tracing/trace_subscriber_stdio.h"
8 #include "base/debug/trace_event.h"
9 #include "base/file_util.h"
10 #include "base/logging.h"
11 #include "base/threading/sequenced_worker_pool.h"
12 #include "content/public/browser/browser_thread.h"
16 // All method calls on this class are done on a SequencedWorkerPool thread.
17 class TraceSubscriberStdioImpl
18 : public base::RefCountedThreadSafe
<TraceSubscriberStdioImpl
> {
20 explicit TraceSubscriberStdioImpl(const base::FilePath
& path
)
26 trace_buffer_
.SetOutputCallback(
27 base::Bind(&TraceSubscriberStdioImpl::Write
, this));
28 file_
= file_util::OpenFile(path_
, "w+");
30 LOG(INFO
) << "Logging performance trace to file: " << path_
.value();
31 trace_buffer_
.Start();
33 LOG(ERROR
) << "Failed to open performance trace file: " << path_
.value();
37 void OnData(const scoped_refptr
<base::RefCountedString
>& data_ptr
) {
38 trace_buffer_
.AddFragment(data_ptr
->data());
42 trace_buffer_
.Finish();
47 friend class base::RefCountedThreadSafe
<TraceSubscriberStdioImpl
>;
49 ~TraceSubscriberStdioImpl() {
53 bool IsValid() const {
54 return file_
&& (0 == ferror(file_
));
62 // This is important, as it breaks a reference cycle.
63 trace_buffer_
.SetOutputCallback(
64 base::debug::TraceResultBuffer::OutputCallback());
67 void Write(const std::string
& output_str
) {
69 size_t written
= fwrite(output_str
.data(), 1, output_str
.size(), file_
);
70 if (written
!= output_str
.size()) {
71 LOG(ERROR
) << "Error " << ferror(file_
) << " in fwrite() to trace file";
79 base::debug::TraceResultBuffer trace_buffer_
;
82 TraceSubscriberStdio::TraceSubscriberStdio(const base::FilePath
& path
)
83 : impl_(new TraceSubscriberStdioImpl(path
)) {
84 BrowserThread::PostBlockingPoolSequencedTask(
86 base::Bind(&TraceSubscriberStdioImpl::OnStart
, impl_
));
89 TraceSubscriberStdio::~TraceSubscriberStdio() {
92 void TraceSubscriberStdio::OnEndTracingComplete() {
93 BrowserThread::PostBlockingPoolSequencedTask(
95 base::Bind(&TraceSubscriberStdioImpl::OnEnd
, impl_
));
98 void TraceSubscriberStdio::OnTraceDataCollected(
99 const scoped_refptr
<base::RefCountedString
>& data_ptr
) {
100 BrowserThread::PostBlockingPoolSequencedTask(
102 base::Bind(&TraceSubscriberStdioImpl::OnData
, impl_
, data_ptr
));
105 } // namespace content