Explore Enterprise Education Gitee Premium Gitee AI AI teammates
Fetch the repository succeeded.
Open Source > Development Lib > Common Toolkit &&
Donate
Please sign in before you donate.
Scan WeChat QR to Pay
Cancel
Complete
Prompt
Switch to Alipay.
OK
Cancel
103 Star 575 Fork 242

cpp-master/cpp-tbox

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
Already have an account? Sign in
文件
develop
Branches (18)
Tags (32)
master
develop
opt/websocket
feat/http-client
feature/tls-crypto-https
fix/jsonrpc
feat/mqtt-reconnect
tidy/doc
wlabs-develop
fix/terminal-mem-leak
feat/use-config-enable-epoll
feature-Broker
opt-loop-wdog
feature-DBus
feature-epoll
feature-update-readme
feature-Dns
feature-TcpSSL
v1.15.5
v1.15.4
v1.14.4
v1.13.10
v1.13.2
v1.12.28
v1.12.25
v1.12.22
v1.12.20
v1.12.10
v1.12.0
v1.11.14
v1.11.12
v1.11.11
v1.11.5
v1.11.4
v1.11.2
v1.11.0
v1.10.27
v1.10.23
develop
Branches (18)
Tags (32)
master
develop
opt/websocket
feat/http-client
feature/tls-crypto-https
fix/jsonrpc
feat/mqtt-reconnect
tidy/doc
wlabs-develop
fix/terminal-mem-leak
feat/use-config-enable-epoll
feature-Broker
opt-loop-wdog
feature-DBus
feature-epoll
feature-update-readme
feature-Dns
feature-TcpSSL
v1.15.5
v1.15.4
v1.14.4
v1.13.10
v1.13.2
v1.12.28
v1.12.25
v1.12.22
v1.12.20
v1.12.10
v1.12.0
v1.11.14
v1.11.12
v1.11.11
v1.11.5
v1.11.4
v1.11.2
v1.11.0
v1.10.27
v1.10.23
Clone or Download
Clone/Download
Prompt
To download the code, please copy the following command and execute it in the terminal
To ensure that your submitted code identity is correctly recognized by Gitee, please execute the following command.
When using the SSH protocol for the first time to clone or push code, follow the prompts below to complete the SSH configuration.
1 Generate RSA keys.
2 Obtain the content of the RSA public key and configure it in SSH Public Keys
To use SVN on Gitee, please visit the usage guide
When using the HTTPS protocol, the command line will prompt for account and password verification as follows. For security reasons, Gitee recommends configure and use personal access tokens instead of login passwords for cloning, pushing, and other operations.
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # Private Token
develop
Branches (18)
Tags (32)
master
develop
opt/websocket
feat/http-client
feature/tls-crypto-https
fix/jsonrpc
feat/mqtt-reconnect
tidy/doc
wlabs-develop
fix/terminal-mem-leak
feat/use-config-enable-epoll
feature-Broker
opt-loop-wdog
feature-DBus
feature-epoll
feature-update-readme
feature-Dns
feature-TcpSSL
v1.15.5
v1.15.4
v1.14.4
v1.13.10
v1.13.2
v1.12.28
v1.12.25
v1.12.22
v1.12.20
v1.12.10
v1.12.0
v1.11.14
v1.11.12
v1.11.11
v1.11.5
v1.11.4
v1.11.2
v1.11.0
v1.10.27
v1.10.23
cpp-tbox
/
modules
/
trace
/
sink.cpp
cpp-tbox
/
modules
/
trace
/
sink.cpp
sink.cpp 12.11 KB
Copy Edit Raw Blame History
海卫哥 authored 2025年05月26日 08:30 +08:00 . opt(trace): 优化日志打印
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
/*
* .============.
* // M A K E / \
* // C++ DEV / \
* // E A S Y / \/ \
* ++ ----------. \/\ .
* \\ \ \ /\ /
* \\ \ \ /
* \\ \ \ /
* -============'
*
* Copyright (c) 2024 Hevake and contributors, all rights reserved.
*
* This file is part of cpp-tbox (https://github.com/cpp-main/cpp-tbox)
* Use of this source code is governed by MIT license that can be found
* in the LICENSE file in the root of the source tree. All contributing
* project authors may be found in the CONTRIBUTORS.md file in the root
* of the source tree.
*/
#include "sink.h"
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <vector>
#include <sstream>
#include <chrono>
#include <sys/syscall.h>
#include <tbox/base/defines.h>
#include <tbox/base/log.h>
#include <tbox/base/assert.h>
#include <tbox/util/fs.h>
#include <tbox/util/string.h>
#include <tbox/util/scalable_integer.h>
namespace tbox {
namespace trace {
void CommitRecordFunc(const char *name, const char *module, uint32_t line,
uint64_t end_timepoint_us, uint64_t duration_us)
{
Sink::GetInstance().commitRecord(name, module, line, end_timepoint_us, duration_us);
}
#define ENDLINE "\n"
namespace {
std::string GetLocalDateTimeStr()
{
char timestamp[16]; //! 固定长度16B,"20220414_071023"
time_t ts_sec = time(nullptr);
struct tm tm;
localtime_r(&ts_sec, &tm);
strftime(timestamp, sizeof(timestamp), "%Y%m%d_%H%M%S", &tm);
return timestamp;
}
}
Sink& Sink::GetInstance()
{
static Sink instance;
return instance;
}
Sink::~Sink()
{
disable();
}
bool Sink::setPathPrefix(const std::string &path_prefix)
{
auto striped_path_prefix = util::string::Strip(path_prefix);
if (striped_path_prefix.empty() || striped_path_prefix.back() == '/') {
LogWarn("path_prefix '%s' is invalid.", path_prefix.c_str());
return false;
}
dir_path_ = striped_path_prefix + '.' + GetLocalDateTimeStr() + '.' + std::to_string(::getpid());
name_list_filename_ = dir_path_ + "/names.txt";
module_list_filename_ = dir_path_ + "/modules.txt";
thread_list_filename_ = dir_path_ + "/threads.txt";
CHECK_CLOSE_RESET_FD(curr_record_fd_);
return true;
}
void Sink::setFileSyncEnable(bool is_enable)
{
is_file_sync_enabled_ = is_enable;
CHECK_CLOSE_RESET_FD(curr_record_fd_);
}
bool Sink::enable()
{
if (is_enabled_)
return true;
if (dir_path_.empty()) {
LogWarn("path_prefix is empty, can't enable.");
return false;
}
using namespace std::placeholders;
util::AsyncPipe::Config config;
config.buff_size = 10240;
config.buff_min_num = 2;
config.buff_max_num = 20;
config.interval = 1000;
async_pipe_.initialize(config);
async_pipe_.setCallback(std::bind(&Sink::onBackendRecvData, this, _1, _2));
is_enabled_ = true;
return true;
}
void Sink::disable()
{
if (is_enabled_) {
is_enabled_ = false;
async_pipe_.cleanup();
CHECK_CLOSE_RESET_FD(curr_record_fd_);
buffer_.hasReadAll();
}
}
void Sink::setFilterExemptSet(const ExemptSet &exempt_set)
{
std::unique_lock<std::mutex> lk(lock_);
filter_exempt_set_ = exempt_set;
}
Sink::ExemptSet Sink::getFilterExemptSet() const
{
std::unique_lock<std::mutex> lk(lock_);
return filter_exempt_set_;
}
bool Sink::isFilterPassed(const std::string &module) const
{
std::unique_lock<std::mutex> lk(lock_);
bool is_in_exempt_set = filter_exempt_set_.find(module) != filter_exempt_set_.end();
if (filter_strategy_ == FilterStrategy::kPermit)
return !is_in_exempt_set;
else
return is_in_exempt_set;
}
void Sink::commitRecord(const char *name, const char *module, uint32_t line, uint64_t end_timepoint_us, uint64_t duration_us)
{
if (!is_enabled_)
return;
auto start_ts = std::chrono::steady_clock::now();
RecordHeader header = {
.thread_id = ::syscall(SYS_gettid),
.end_ts_us = end_timepoint_us,
.duration_us = duration_us,
.line = line,
.name_size = ::strlen(name) + 1,
.module_size = ::strlen(module) + 1
};
async_pipe_.appendLock();
async_pipe_.appendLockless(&header, sizeof(header));
async_pipe_.appendLockless(name, header.name_size);
async_pipe_.appendLockless(module, header.module_size);
async_pipe_.appendUnlock();
auto time_cost = std::chrono::steady_clock::now() - start_ts;
if (time_cost > std::chrono::milliseconds(100))
LogNotice("trace commit cost > 100 ms, %lu us, %s at L%d", time_cost.count() / 1000, name, line);
}
void Sink::onBackendRecvData(const void *data, size_t size)
{
auto start_ts = std::chrono::steady_clock::now();
if (!checkAndCreateRecordFile() ||
!checkAndWriteNames() ||
!checkAndWriteModules() ||
!checkAndWriteThreads())
return;
buffer_.append(data, size);
std::vector<uint8_t> write_cache;
while (buffer_.readableSize() > sizeof(RecordHeader)) {
RecordHeader header;
::memcpy(&header, buffer_.readableBegin(), sizeof(header));
//! Q: 为什么不直接引用,像这样 auto *phead = static_cast<const RecordHeader*>(buffer_.readableBegin())
// 而是要先copy到header再使用?
//! A: 因为直接指针引用会有对齐的问题。
auto packet_size = header.name_size + header.module_size + sizeof(header);
//! 如果长度不够,就跳过,等下一次
if (packet_size > buffer_.readableSize()) {
TBOX_ASSERT(packet_size < 1024); //! 正常不应该超过1K的,如果真超过了就是Bug
break;
}
buffer_.hasRead(sizeof(header));
const char *name = reinterpret_cast<const char*>(buffer_.readableBegin());
const char *module = name + header.name_size;
onBackendRecvRecord(header, name, module, write_cache);
buffer_.hasRead(header.name_size + header.module_size);
}
if (!write_cache.empty()) {
auto wsize = ::write(curr_record_fd_, write_cache.data(), write_cache.size());
if (wsize != static_cast<ssize_t>(write_cache.size())) {
LogErrno(errno, "write record file '%s' fail", curr_record_filename_.c_str());
return;
}
total_write_size_ += wsize;
if (total_write_size_ >= record_file_max_size_)
CHECK_CLOSE_RESET_FD(curr_record_fd_);
}
auto time_cost = std::chrono::steady_clock::now() - start_ts;
if (time_cost > std::chrono::milliseconds(100))
LogNotice("trace sink cost > 100 ms, %lu us", time_cost.count() / 1000);
}
void Sink::onBackendRecvRecord(const RecordHeader &record, const char *name, const char *module, std::vector<uint8_t> &write_cache)
{
if (!isFilterPassed(module))
return;
auto thread_index = allocThreadIndex(record.thread_id);
auto name_index = allocNameIndex(name, record.line);
auto module_index = allocModuleIndex(module);
auto time_diff = record.end_ts_us - last_timepoint_us_;
constexpr size_t kBufferSize = 40;
uint8_t buffer[kBufferSize];
size_t data_size = 0;
data_size += util::DumpScalableInteger(time_diff, (buffer + data_size), (kBufferSize - data_size));
data_size += util::DumpScalableInteger(record.duration_us, (buffer + data_size), (kBufferSize - data_size));
data_size += util::DumpScalableInteger(thread_index, (buffer + data_size), (kBufferSize - data_size));
data_size += util::DumpScalableInteger(name_index, (buffer + data_size), (kBufferSize - data_size));
data_size += util::DumpScalableInteger(module_index, (buffer + data_size), (kBufferSize - data_size));
last_timepoint_us_ = record.end_ts_us;
std::back_insert_iterator<std::vector<uint8_t>> back_insert_iter(write_cache);
std::copy(buffer, buffer + data_size, back_insert_iter);
}
bool Sink::checkAndCreateRecordFile()
{
if (curr_record_fd_ >= 0) {
if (util::fs::IsFileExist(curr_record_filename_))
return true;
CHECK_CLOSE_RESET_FD(curr_record_fd_);
}
std::string records_path = dir_path_ + "/records";
//!检查并创建路径
if (!util::fs::MakeDirectory(records_path, false)) {
LogErrno(errno, "create directory '%s' fail", records_path.c_str());
return false;
}
std::string datatime_str = GetLocalDateTimeStr();
std::string new_record_filename;
int postfix = 0;
do {
new_record_filename = records_path + '/' + datatime_str + ".bin";
if (postfix != 0) {
new_record_filename += '.';
new_record_filename += std::to_string(postfix);
}
++postfix;
} while (util::fs::IsFileExist(new_record_filename)); //! 避免在同一秒多次创建日志文件,都指向同一日志名
curr_record_filename_ = std::move(new_record_filename);
int flags = O_CREAT | O_WRONLY | O_APPEND;
if (is_file_sync_enabled_)
flags |= O_DSYNC;
curr_record_fd_ = ::open(curr_record_filename_.c_str(), flags, S_IRUSR | S_IWUSR);
if (curr_record_fd_ < 0) {
LogErrno(errno, "open record file '%s' fail", curr_record_filename_.c_str());
return false;
}
total_write_size_ = 0;
last_timepoint_us_ = 0;
return true;
}
bool Sink::checkAndWriteNames()
{
//! 如果文件不存在了,则重写所有的名称列表
if (!util::fs::IsFileExist(name_list_filename_)) {
std::vector<std::string> name_vec(name_to_index_map_.size());
for (auto &item : name_to_index_map_)
name_vec[item.second] = item.first;
std::ostringstream oss;
for (auto &content: name_vec)
oss << content << ENDLINE;
return util::fs::WriteStringToTextFile(name_list_filename_, oss.str(), is_file_sync_enabled_);
}
return true;
}
bool Sink::checkAndWriteModules()
{
//! 如果文件不存在了,则重写所有的模块列表
if (!util::fs::IsFileExist(module_list_filename_)) {
std::vector<std::string> module_vec(module_to_index_map_.size());
for (auto &item : module_to_index_map_)
module_vec[item.second] = item.first;
std::ostringstream oss;
for (auto &module : module_vec)
oss << module << ENDLINE;
return util::fs::WriteStringToTextFile(module_list_filename_, oss.str(), is_file_sync_enabled_);
}
return true;
}
bool Sink::checkAndWriteThreads()
{
//! 如果文件不存在了,则重写所有的线程列表
if (!util::fs::IsFileExist(thread_list_filename_)) {
std::vector<int> thread_vec(thread_to_index_map_.size());
for (auto &item : thread_to_index_map_)
thread_vec[item.second] = item.first;
std::ostringstream oss;
for (auto thread_id : thread_vec)
oss << thread_id << ENDLINE;
return util::fs::WriteStringToTextFile(thread_list_filename_, oss.str(), is_file_sync_enabled_);
}
return true;
}
Sink::Index Sink::allocNameIndex(const std::string &name, uint32_t line)
{
std::string content = name + " at L" + std::to_string(line);
auto iter = name_to_index_map_.find(content);
if (iter != name_to_index_map_.end())
return iter->second;
auto new_index = next_name_index_++;
name_to_index_map_[content] = new_index;
util::fs::AppendStringToTextFile(name_list_filename_, content + ENDLINE, is_file_sync_enabled_);
return new_index;
}
Sink::Index Sink::allocModuleIndex(const std::string &module)
{
auto iter = module_to_index_map_.find(module);
if (iter != module_to_index_map_.end())
return iter->second;
auto new_index = next_module_index_++;
module_to_index_map_[module] = new_index;
util::fs::AppendStringToTextFile(module_list_filename_, module + ENDLINE, is_file_sync_enabled_);
return new_index;
}
Sink::Index Sink::allocThreadIndex(long thread_id)
{
auto iter = thread_to_index_map_.find(thread_id);
if (iter != thread_to_index_map_.end())
return iter->second;
auto new_index = next_thread_index_++;
thread_to_index_map_[thread_id] = new_index;
util::fs::AppendStringToTextFile(thread_list_filename_, std::to_string(thread_id) + ENDLINE, is_file_sync_enabled_);
return new_index;
}
}
}
Loading...
Report
Report success
We will send you the feedback within 2 working days through the letter!
Please fill in the reason for the report carefully. Provide as detailed a description as possible.
Please select a report type
Cancel
Send
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

About

cpp-tbox是一个Linux C++,MIT开源许可的,基于 Reactor 模式的开发框架与组件库。它主要针对智能硬件、机器人、网络服务等开发领域。 它提供了一套易于开发、稳定可靠的框架,有:通信库(TCP/UDP/串口)、HTTP、线程池、定时器池、协程、日志、命令终端、状态机、行为树等非常实用的开发组件,以及完备实用的主框架,能为广大开发者节省大量开发与调试时间。
Cancel

Releases

No release

The Open Source Evaluation Index is derived from the OSS Compass evaluation system, which evaluates projects around the following three dimensions

1. Open source ecosystem

  • Productivity: To evaluate the ability of open-source projects to output software artifacts and open-source value.
  • Innovation: Used to evaluate the degree of diversity of open source software and its ecosystem.
  • Robustness: Used to evaluate the ability of open-source projects to resist internal and external interference and self recover in the face of changing development environments.

2. Collaboration, People, Software

  • Collaboration: represents the degree and depth of collaboration in open source development behavior.
  • Observe the influence of core personnel in open source projects, and examine the evaluations of users and developers on open source projects from a third-party perspective.
  • Software: Evaluate the value of products exported from open-source projects and their ultimate destination. It is also a concrete manifestation of "open source software", one of the oldest mainstream directions in open source evaluation.

3. Evaluation model

    Based on the dimensions of "open source ecosystem" and "collaboration, people, and software", identify quantifiable indicators directly or indirectly related to this goal, quantitatively evaluate the health and ecology of open source projects, and ultimately form an open source evaluation index.

Contributors

All

Activities

can not load any more
Edit
About
Homepage
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/cpp-master/cpp-tbox.git
git@gitee.com:cpp-master/cpp-tbox.git
cpp-master
cpp-tbox
cpp-tbox
develop
Going to Help Center

Search

Comment
Repository Report
Back to the top
Login prompt
This operation requires login to the code cloud account. Please log in before operating.
Go to login
No account. Register

AltStyle によって変換されたページ (->オリジナル) /