mpacklog — Log dictionaries to file using MessagePack  v2.1.0
Logger.h
Go to the documentation of this file.
1 /*
2  * Copyright 2022 Stéphane Caron
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  * This file incorporates work covered by the following copyright and
17  * permission notice:
18  *
19  * Logger class of mc_rtc
20  * Copyright 2015-2019 CNRS-UM LIRMM, CNRS-AIST JRL
21  * License: BSD-2-Clause (see licenses/LICENSE-mc_rtc)
22  */
23 
24 #pragma once
25 
26 #include <palimpsest/Dictionary.h>
27 
28 #include <fstream>
29 #include <string>
30 #include <thread>
31 #include <utility>
32 #include <vector>
33 
34 #include "mpacklog/CircularBuffer.h"
35 
37 namespace mpacklog {
38 
39 using palimpsest::Dictionary;
40 
48 constexpr size_t kBufferSize = 1024;
49 
66 class Logger {
67  public:
73  explicit Logger(const std::string &path, bool append = false);
74 
76  ~Logger();
77 
89  bool put(char *data, size_t size);
90 
99  inline bool put(const Dictionary &dict) {
100  size_t size = dict.serialize(serialization_buffer_);
101  return Logger::put(serialization_buffer_.data(), size);
102  }
103 
105  size_t last_size() const { return last_size_; }
106 
107  private:
109  void flush_buffer();
110 
111  private:
113  std::ofstream file_;
114 
116  std::thread thread_;
117 
119  bool keep_going_ = true;
120 
123 
125  std::pair<char *, size_t> pop_;
126 
133  std::vector<char> serialization_buffer_;
134 
136  size_t last_size_ = 0;
137 };
138 
139 } // namespace mpacklog
mpacklog::Logger::~Logger
~Logger()
Stop the logging thread.
Definition: Logger.cpp:56
mpacklog::CircularBuffer
Definition: CircularBuffer.h:38
mpacklog::Logger
Multi-threaded logger.
Definition: Logger.h:66
mpacklog
Log action and observation dictionaries to MessagePack binary files.
Definition: CircularBuffer.h:30
mpacklog::Logger::Logger
Logger(const std::string &path, bool append=false)
Open a new log file and start the logging thread.
Definition: Logger.cpp:30
mpacklog::Logger::last_size
size_t last_size() const
Size of the last message in bytes.
Definition: Logger.h:105
mpacklog::Logger::put
bool put(const Dictionary &dict)
Save a dictionary to be written to the log.
Definition: Logger.h:99
mpacklog::Logger::put
bool put(char *data, size_t size)
Save data to be written to the log.
Definition: Logger.cpp:64
mpacklog::kBufferSize
constexpr size_t kBufferSize
Number of slots in the internal circular buffer.
Definition: Logger.h:48