【发布时间】:2017-09-22 17:44:04
【问题描述】:
我已经解决了许多标题相同或相似的问题,我已经以多种方式更改了代码,我什至数不清....我遇到了一个有趣的问题。
我有一个非常简单的日志类,只需将内容写入文件。完全相同的代码在构造函数中有效,但在成员函数中无效。我去掉了一些不相关的代码,剩下的就是:
private:
std::string logfile_path_;
std::string program_name_;
std::string GetTimestamp() {
timeval tv;
gettimeofday(&tv, NULL);
char cTimestamp[24];
strftime(cTimestamp, sizeof(cTimestamp), "%F %T", std::localtime(&tv.tv_sec));
sprintf(&cTimestamp[19], ".%03d", (tv.tv_usec / 1000)); // write the miliseconds (microseconds/1000) into cTimestamp starting at the 20th character. %03d == pad with 0, for a minimum length of 3, an integer.
return cTimestamp; // function returns std::string so this will be implicitly cast into a string and returned.
}
public:
int log_level_;
SrxDsLog(std::string Logfile_path, std::string program_name, int log_level) {
log_level_ = log_level;
program_name_ = program_name;
logfile_path_ = Logfile_path;
std::ofstream logfile(logfile_path_.c_str(), std::ios::out | std::ios::app);
std::cout << "Logger started, Log file: " << logfile_path_ << std::endl;
logfile << "Logger started, Log file: " << logfile_path_ << std::endl;
return;
}
void WriteLog(std::string Log_message, int Severity = LOG_CRITICAL, std::string Function_name = "") {
if (Severity >= log_level_) {
std::cout << GetTimestamp() << "|" << program_name_ << "|" << Function_name << "|" << GetSeverity(Severity) << "|" << Log_message << std::endl;
std::ofstream logfile(logfile_path_.c_str(), std::ios::out | std::ios::app);
logfile << GetTimestamp() << "|" << program_name_ << "|" << Function_name << "|" << GetSeverity(Severity) << "|" << Log_message << std::endl;
}
}
问题是为什么它在构造函数中工作,但完全相同的代码在成员函数中不起作用。 std::cout 正在写我想要的完全相同的日志消息,但它没有出现在文件中。每次运行程序时,该文件都包含一行。
【问题讨论】:
-
呃,也就是 不 ctor 和成员函数中的完全相同的代码。事实上,它不应该编译,因为
logfile只存在于 ctor 中。 -
我在两个函数中都声明了日志文件。
-
@NeilButterworth 还有什么选择?不记录是不是。我想我可以重定向 cout 和 cerr ??在那里节省的精力可以忽略不计。
-
你没有在任何地方设置
log_level_成员,所以它仍然是未初始化的。 -
在
std::ofstream logfile...行之后,你应该check to see if the file actually is opened。