I'm writing a multi-threaded system using c++. I defined a log object as global variable, and all threads write logs into this object.
Log class is defined as follow.
log.h
#ifndef LOG_H_
#define LOG_H_
#include <string>
#include <fstream>
#include <mutex>
enum class LogType{
ERROR,
WARNING,
INFO,
DEBUG
};
class ContentsCopyLog
{
public:
bool open(std::string logFile);
void write(LogType type, std::string msg);
void close();
private:
std::fstream f_;
std::mutex mtx_;
};
#endif
log.cpp
#include <string>
#include <fstream>
#include <chrono>
#include <time.h>
#include <iostream>
#include "log.h"
bool ContentsCopyLog::open(std::string logFile)
{
f_.open(logFile, std::fstream::out | std::fstream::app);
if(!f_.is_open()){
return false;
}
return true;
}
void ContentsCopyLog::write(LogType type, std::string msg)
{
auto now = std::chrono::system_clock::now();
std::time_t current_time = std::chrono::system_clock::to_time_t(now);
std::lock_guard<std::mutex> lck(mtx_);
char buf[100];
strftime(buf, 100, "%Y-%m-%d %H:%M:%S ", localtime(¤t_time));
f_ << buf;
if(type == LogType::ERROR){
f_ << "[ERROR ] ";
}else if(type == LogType::WARNING){
f_ << "[WARNING] ";
}else if(type == LogType::INFO){
f_ << "[INFO ] ";
}else if(type == LogType::DEBUG){
f_ << "[DEBUG ] ";
}
f_ << msg << std::endl;
}
void ContentsCopyLog::close()
{
if(f_.is_open()){
f_.close();
}
}
All worker threads execute the same function. In this function some logs will be written into the log file.
The problem now is it seems logs from some threads have not been written into the log file. Any idea?