OLD | NEW |
1 // Copyright 2014 The Chromium Authors. All rights reserved. | 1 // Copyright 2014 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "services/tracing/trace_data_sink.h" | 5 #include "services/tracing/trace_data_sink.h" |
6 | 6 |
7 #include "base/files/file_util.h" | 7 #include "base/logging.h" |
8 | 8 |
9 namespace tracing { | 9 namespace tracing { |
| 10 namespace { |
10 | 11 |
11 TraceDataSink::TraceDataSink(base::FilePath base_name) : empty_(true) { | 12 const char kStart[] = "{\"traceEvents\":["; |
12 file_ = | 13 const char kEnd[] = "]}"; |
13 base::OpenFile(base_name.AddExtension(FILE_PATH_LITERAL(".trace")), "w+"); | 14 |
14 static const char start[] = "{\"traceEvents\":["; | 15 void Write(const mojo::ScopedDataPipeProducerHandle& pipe, |
15 fwrite(start, 1, strlen(start), file_); | 16 const char* string, |
| 17 uint32_t num_bytes) { |
| 18 CHECK_EQ(MOJO_RESULT_OK, |
| 19 mojo::WriteDataRaw(pipe.get(), string, &num_bytes, |
| 20 MOJO_WRITE_DATA_FLAG_ALL_OR_NONE)); |
| 21 } |
| 22 } |
| 23 |
| 24 TraceDataSink::TraceDataSink(mojo::ScopedDataPipeProducerHandle pipe) |
| 25 : pipe_(pipe.Pass()), empty_(true) { |
| 26 Write(pipe_, kStart, strlen(kStart)); |
16 } | 27 } |
17 | 28 |
18 TraceDataSink::~TraceDataSink() { | 29 TraceDataSink::~TraceDataSink() { |
19 if (file_) | 30 if (pipe_.is_valid()) |
20 Flush(); | 31 Flush(); |
21 DCHECK(!file_); | 32 DCHECK(!pipe_.is_valid()); |
22 } | 33 } |
23 | 34 |
24 void TraceDataSink::AddChunk(const std::string& json) { | 35 void TraceDataSink::AddChunk(const std::string& json) { |
25 if (!empty_) { | 36 if (!empty_) |
26 fwrite(",", 1, 1, file_); | 37 Write(pipe_, ",", 1); |
27 } | |
28 | |
29 empty_ = false; | 38 empty_ = false; |
30 | 39 Write(pipe_, json.data(), json.length()); |
31 fwrite(json.data(), 1, json.length(), file_); | |
32 } | 40 } |
33 | 41 |
34 void TraceDataSink::Flush() { | 42 void TraceDataSink::Flush() { |
35 static const char end[] = "]}"; | 43 Write(pipe_, kEnd, strlen(kEnd)); |
36 fwrite(end, 1, strlen(end), file_); | 44 pipe_.reset(); |
37 base::CloseFile(file_); | |
38 file_ = nullptr; | |
39 } | 45 } |
40 | 46 |
41 } // namespace tracing | 47 } // namespace tracing |
OLD | NEW |