동일한 제목이나 비슷한 제목으로 많은 질문을 던졌고 여러 가지 방법으로 코드를 변경했습니다. 흥미로운 문제가있다.
로깅을위한 클래스가 매우 간단하며 파일에 물건을 씁니다. 정확한 코드는 생성자에서 작동하지만 멤버 함수에서는 작동하지 않습니다. 나는 어떤 관련이없는 코드를 제거하고있어, 나머지는 : 그것은 생성자에서 일하고 있지만, 동일한 코드는 멤버 함수에서 작동하지 않는 이유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은 내가 원하는 정확한 로그 메시지를 쓰고 있지만 파일에 나타나지 않습니다. 파일은 프로그램이 실행될 때마다 한 행을 포함합니다.
Er, ctor 및 멤버 함수에서 똑같은 코드는 아닙니다. 사실'logfile'은 ctor에만 존재하기 때문에 컴파일해서는 안됩니다. –
두 함수에서 logfile을 선언하고 있습니다. – xyious
@NeilButterworth 대체 무엇입니까? 로깅되지 않습니다. 나는 내가 cout과 cerr을 방향 전환 할 수 있다고 생각하니? 거기에서 절약 된 노력의 양은 무시할 만합니다. – xyious