簡體   English   中英

用 C/C++ 編寫日志文件

[英]Writing a Log file in C/C++

我想用 C++ 寫一個日志文件。 我正在處理某些事情,因此我需要維護我處理的事情的屬性日志,以便我可以恢復到此日志文件以查看我特別感興趣的任何內容的屬性......有人可以幫助我嗎在實現這一目標?

記錄日志的標准方法(根據我的經驗)是使用 stdout 或 stderr 流。 在 C++ 中使用這些你需要包含 iostream,並使用如下:

#include <iostream>

int main(int argc, char* argv[])
{
  using std::cout;
  using std::cerr;
  using std::endl;

  cout << "Output message" << endl;
  cerr << "Error message" << endl;
}

然而,這只能實現打印到那些通常在終端結束的輸出。 如果您想使用這些標准流方法(它們非常易讀)輸出到文件,那么您必須以某種方式重定向輸出。 一種方法是使用 cstdio 提供的freopen函數。 它的作用是打開一個文件,並將給定的流移動到該文件。 有關文檔,請參見此處 一個例子是:

#include <iostream>
#include <cstdio>

int main(int argc, char* argv[])
{
  using namespace std;
  freopen( "output.txt", "w", stdout );
  freopen( "error.txt", "w", stderr );

  cout << "Output message" << endl;
  cerr << "Error message" << endl;
}

(我已改為using namespace std;只是為了簡潔起見。)

您正在將標准輸出流stdout (由cout )移動到 output.txt(在寫入模式下),並且您正在將stderr (由cerr )移動到 error.txt 也在寫入模式下。

希望這能解決問題。

這非常方便,只需插入一些通用頭文件即可從程序中的任何位置調用(更好的方法是使用這些函數形成一個類)

inline string getCurrentDateTime( string s ){
    time_t now = time(0);
    struct tm  tstruct;
    char  buf[80];
    tstruct = *localtime(&now);
    if(s=="now")
        strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct);
    else if(s=="date")
        strftime(buf, sizeof(buf), "%Y-%m-%d", &tstruct);
    return string(buf);
};
inline void Logger( string logMsg ){

    string filePath = "/somedir/log_"+getCurrentDateTime("date")+".txt";
    string now = getCurrentDateTime("now");
    ofstream ofs(filePath.c_str(), std::ios_base::out | std::ios_base::app );
    ofs << now << '\t' << logMsg << '\n';
    ofs.close();
}

用法:Logger("這是日志消息"); 寫入文件(或追加現有文件)

/somedir/log_2017-10-20.txt 

內容:

2017-10-20 09:50:59 This is log message

您嘗試做的事情太深入,無法提供有關堆棧溢出的完整解決方案。 您可以做的是查看您選擇的日志庫的文檔。 就我而言,這是Boost.Log ,它是Boost C++ 庫的日志庫,其文檔可在 此處找到。

它在我剛剛鏈接到的頁面底部指出

盡管該庫已通過審核並被臨時接受,但它不是 Boost 庫集合的官方部分。 審查結果可在此處獲得

所以你會怎么做。

為什么不使用許多可用的日志框架之一,比如Apache log4cxx 我建議這樣做而不是嘗試自己動手 - 為什么要重新發明輪子?

您可能還想考慮https://github.com/johnwbyrd/logog 它是一個面向性能的 C++ 日志系統。 但是,如果這對您的項目來說有點過於緊張,那么好的舊 cerr 和 cout 可以很好地解決這個問題。

非常感謝所有的回復...我認為我正在尋找的答案是,甚至UTF8中的日志文件的格式就像一個txt文件所以c在編寫帶有簡單文件的那種文件時沒有問題寫它提供。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM