2017-09-22 443 views
-3

我已经用相同或相似的标题去了很多问题,我已经在许多方面改变了代码,我甚至不能算......有一个有趣的问题。
我有一个非常简单的日志记录类,只是将东西写入文件。完全相同的代码在构造函数中工作,但在成员函数中不起作用。我剥出来一些不相干的代码,其余的是:std :: ofstream不会写入文件(有时)

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正在写入我想要的完全相同的日志消息,但它没有出现在文件中。每次程序运行时,该文件都包含一行。

+0

呃,那就是ctor和成员函数中的_not_完全相同的代码。事实上,它不应该编译,因为'logfile'只存在于ctor中。 –

+0

我在这两个函数中声明了日志文件。 – xyious

+0

@NeilButterworth有什么选择?不记录是不是。我想我可以重定向cout和cerr?节省的努力量可以忽略不计。 – xyious

回答

2

在一个令人惊讶的不满情绪变化的事件中,我投票结束了我的问题。
这个问题显然是由不相关的代码中的未定义行为造成的。那是因为我做了一些在C++ 11中定义的东西,但不在C++ 03中。显然你不能从构造函数调用构造函数在C + + 03 ...
因此,并且因为问题没有包含实际上有错的代码,这个问题似乎非常糟糕。

请关闭。

1
int log_level_; 

构造函数无法初始化此类成员。

随后,与此类成员的比较会导致未定义的行为。

+0

我以为班级成员是zerod?无论哪种方式,我得到一个输出,我以前写了log_level_在cout的消息,它返回0,直到我明确地设置它。 – xyious

+0

无论如何,它被评估一次,然后我写入cout(成功)并写入日志文件(失败)。这在逻辑上不能成为答案。 – xyious

+0

@xyious在C++中的初始化规则有点混乱,但在这种情况下,原始的'int'将保持未初始化。它可能是0,也可能不是,这取决于内存的状态。但是,从未初始化的变量读取是未定义的行为,所以关于前面的'if'语句的任何逻辑都会被抛出窗口。 – 0x5453