1 // Copyright 2020 The Pigweed Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 // use this file except in compliance with the License. You may obtain a copy of 5 // the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations under 13 // the License. 14 //============================================================================== 15 // 16 17 #pragma once 18 19 #include <stdio.h> 20 21 #include <fstream> 22 23 #include "pw_trace/example/sample_app.h" 24 #include "pw_trace_tokenized/trace_callback.h" 25 26 namespace pw { 27 namespace trace { 28 29 class TraceToFile { 30 public: TraceToFile(const char * file_name)31 TraceToFile(const char* file_name) { 32 Callbacks::Instance().RegisterSink(TraceSinkStartBlock, 33 TraceSinkAddBytes, 34 TraceSinkEndBlock, 35 &out_, 36 &sink_handle_); 37 out_.open(file_name, std::ios::out | std::ios::binary); 38 } 39 ~TraceToFile()40 ~TraceToFile() { 41 Callbacks::Instance().UnregisterSink(sink_handle_); 42 out_.close(); 43 } 44 TraceSinkStartBlock(void * user_data,size_t size)45 static void TraceSinkStartBlock(void* user_data, size_t size) { 46 std::ofstream* out = reinterpret_cast<std::ofstream*>(user_data); 47 uint8_t b = static_cast<uint8_t>(size); 48 out->write(reinterpret_cast<const char*>(&b), sizeof(b)); 49 } 50 TraceSinkAddBytes(void * user_data,const void * bytes,size_t size)51 static void TraceSinkAddBytes(void* user_data, 52 const void* bytes, 53 size_t size) { 54 std::ofstream* out = reinterpret_cast<std::ofstream*>(user_data); 55 out->write(reinterpret_cast<const char*>(bytes), size); 56 } 57 TraceSinkEndBlock(void * user_data)58 static void TraceSinkEndBlock(void* user_data) { 59 std::ofstream* out = reinterpret_cast<std::ofstream*>(user_data); 60 out->flush(); 61 } 62 63 private: 64 std::ofstream out_; 65 CallbacksImpl::SinkHandle sink_handle_; 66 }; 67 68 } // namespace trace 69 } // namespace pw 70