私は同じタイトルまたは類似のタイトルで多くの質問をしましたが、私は数え切れないほど多くの方法でコードを変更しました....興味深い問題があります。
私は非常にシンプルで、ファイルに物事を書き込むためのクラスを持っています。まったく同じコードはコンストラクタで機能しますが、メンバ関数では機能しません。私はいくつかの無関係なコードを除去しています、残りは次のとおりです。それは、コンストラクタで働いているが、正確な同じコードはメンバ関数で働いていない理由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は私が望むのと全く同じログメッセージを書いていますが、ファイルには表示されません。このファイルには、プログラムが実行されるたびに1行が含まれます。
Er、それはctorとメンバ関数で全く同じコードではありません。実際、 'logfile'はctorにしか存在しないので、コンパイルすべきではありません。 –
私は両方の関数でlogfileを宣言しています。 – xyious
@NeilButterworth何が代わりですか?ロギングではありません。私はcoutとcerrをリダイレクトできると思いますか?そこに保存された労力の量はごくわずかです。 – xyious