日志是GitHub开源项目,链接
使用
sudo apt install libgoogle-glog-dev
# 编译
g++ test.cpp -lpthread -lglog
一、多线程
1、std::cout 多线程打印
void taskFunction(int taskId) {
std::cout << "Task " << taskId << " is running in thread " << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
日志,明显错乱
2、glog打印
void taskFunction(int taskId) {
LOG(INFO) << "Task " << taskId << " is running in thread " << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
日志,格式清晰./a.out > 1.txt 2>&1
二、glog示例
#include <glog/logging.h>
int main(int argc, char* argv[]) {
google::InitGoogleLogging(argv[0]);
LOG(INFO) << "Found " << " cookies" << std::endl;
LOG(ERROR) << "Found " << " cookies" << std::endl;
}
编译执行
g++ test.cpp -lglog
GLOG_logtostderr=1 ./a.out
# 不加GLOG_logtostderr=1 info级别日志不打印