【问题标题】:How can I write some trace in my log file in C++如何在 C++ 中的日志文件中写入一些跟踪
【发布时间】:2014-10-18 09:08:01
【问题描述】:

我想在我的日志文件中写入文件的执行日期和执行结束时间。

我不能安装任何东西,只能使用标准模块(我在 linux 命令行中执行我的代码)。

我想要这样的东西: [TRACE] 2014-07-24 14:18:50,2014-07-24 14:18:52

我暂时有这个结果:

[TRACE] , Start date of execution : Aug 25 2014 : 10:43:02 End date of execution : Mon Aug 25 10:43:06 2014

这里是我的代码:

#include <iostream>
#include <string>
#include <fstream>
#include <ctime>

using namespace std;

void startDateExecution(fstream& file) {

    if(fichier)
    {
         file << "[TRACE]" << " , " << "Start date of execution : " << __DATE__ << " : " << __TIME__ << endl;     
    }
    else
         cerr << "Unable to open file" << endl;
}

void endDateExecution(fstream& file) {

        time_t result = time(NULL);
        file << "End date of execution : " << asctime(localtime(&result)) << endl;

        file.close();
}

void displayDate(fstream& file) {

     startDateExecution(file);
     endDateExecution(file);         
}

int main(){

      fstream file("trace.log", ios::out | ios::trunc);
      displayDate(file);
      return 0;  
}

【问题讨论】:

  • 问题到底是什么?如何更改打印日期的格式..?
  • 首先我想知道,如果那是文件的执行日期,然后,是的,我想要这种格式:[TRACE],module_name,2014-07-24 14:18:50,2014 -07-24 14:18:52
  • 您需要查看 time localtimeasctimestrftime 等函数。 __DATE__ 等是指编译的日期和时间。 en.cppreference.com/w/cpp/chrono/c/timeen.cppreference.com/w/cpp/chrono/c/strftime
  • module_name 应该是什么?
  • 是的,所以我的执行结束日期是好的,但开始日期不好?

标签: c++ trace logfiles logfile


【解决方案1】:

正如许多人评论的那样,__DATE____TIME__ 指的是编译时间,而不是执行时间。
您需要在执行开始和结束时检索当前时间;在这两种情况下,无论您使用哪种方法,您都将使用相同的方法。

这是一个如何使用 strftime 格式化时间的示例。

std::string format(time_t when)
{
    char timestr[256] = {0};
    const char* my_format = "%m/%d/%y @ %H:%M:%S"; 
    std::strftime(timestr, sizeof(timestr), my_format, std::localtime(&when));
    return timestr;
}

你会这样使用它:

int main()
{
    time_t start = std::time(NULL);
    // Do stuff
    time_t end = std::time(NULL);

   std::cout << "Start: " << format(start) << std::endl
             << "End: "   << format(end)   << std::endl;
}

阅读the documentation for strftime,了解如何指定自己的格式。

【讨论】:

  • 你能告诉我我的代码吗,因为我尝试使用你的代码但我有错误。
【解决方案2】:

您可以使用 log4cpp 库。它还有很多其他功能。以下网站提供了示例程序。

http://log4cpp.sourceforge.net/

您只需要根据需要实例化 appender。我在我的项目中使用了 RollingFileAppender,我需要在某个阈值之后划分日志文件(即文件大小达到 1MB)。然后您需要设置您希望写入日志的模式。

希望这会有所帮助。

【讨论】:

  • 问题,我不能安装任何东西,我在脚本中编写代码并在命令行(Linux)中执行它。
  • 为什么不能安装任何东西?建议的库很简单,可以满足您的需要。我建议您编辑您的问题,以便让我们更好地了解您的情况。
  • 因为在我的办公室我没有权限,我们不能安装任何东西,只使用标准模块:(,我想获得我的文件执行的这种格式:[TRACE] ,module_name,2014-07-24 14:18:50,2014-07-24 14:18:52
  • do not post an answer that consists essentially of a link。在你的答案中包括要点;留下链接以获取更多信息或作为参考。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-09
  • 2012-03-11
  • 1970-01-01
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
相关资源
最近更新 更多