如何将消息时间戳写入日志文件? 我试图为我的C++程序创建日志文件。我的目标是在程序的两个点上放置两个时间戳,并在文件中打印这两个点之间的CPU时间段。我这样做是因为我想知道我的代码的哪些部分最耗时,这样我就可以进行改进(因此可能有几个代码块我想要度量)。到目前为止,我已经创建了一个函数,当调用该函数时,它会将作为参数传递的字符串打印到一个文件: #define LOGFILE "myprog.log" void Log (std::string message){ std::ofstream ofs; ofs.open(LOGFILE, std::ofstream::out | std::ios::app); ofs << message << std::endl; ofs.close(); } #定义日志文件“myprog.log” 无效日志(std::字符串消息){ std::ofs流; open(日志文件,std::ofstream::out | std::ios::app); ofs

如何将消息时间戳写入日志文件? 我试图为我的C++程序创建日志文件。我的目标是在程序的两个点上放置两个时间戳,并在文件中打印这两个点之间的CPU时间段。我这样做是因为我想知道我的代码的哪些部分最耗时,这样我就可以进行改进(因此可能有几个代码块我想要度量)。到目前为止,我已经创建了一个函数,当调用该函数时,它会将作为参数传递的字符串打印到一个文件: #define LOGFILE "myprog.log" void Log (std::string message){ std::ofstream ofs; ofs.open(LOGFILE, std::ofstream::out | std::ios::app); ofs << message << std::endl; ofs.close(); } #定义日志文件“myprog.log” 无效日志(std::字符串消息){ std::ofs流; open(日志文件,std::ofstream::out | std::ios::app); ofs,c++,logging,time,timestamp,chrono,C++,Logging,Time,Timestamp,Chrono,我通常使用我的实现来实现这些事情 #include <chrono> #include <ctime> // strftime format #define LOGGER_PRETTY_TIME_FORMAT "%Y-%m-%d %H:%M:%S" // printf format #define LOGGER_PRETTY_MS_FORMAT ".%03d" // convert current time to milliseconds since unix

我通常使用我的实现来实现这些事情

#include <chrono>
#include <ctime>


// strftime format
#define LOGGER_PRETTY_TIME_FORMAT "%Y-%m-%d %H:%M:%S"

// printf format
#define LOGGER_PRETTY_MS_FORMAT ".%03d"


// convert current time to milliseconds since unix epoch
template <typename T>
static int to_ms(const std::chrono::time_point<T>& tp)
{
    using namespace std::chrono;

    auto dur = tp.time_since_epoch();
    return static_cast<int>(duration_cast<milliseconds>(dur).count());
}


// format it in two parts: main part with date and time and part with milliseconds
static std::string pretty_time()
{
    auto tp = std::chrono::system_clock::now();
    std::time_t current_time = std::chrono::system_clock::to_time_t(tp);

    // this function use static global pointer. so it is not thread safe solution
    std::tm* time_info = std::localtime(&current_time);

    char buffer[128];

    int string_size = strftime(
        buffer, sizeof(buffer),
        LOGGER_PRETTY_TIME_FORMAT,
        time_info
    );

    int ms = to_ms(tp) % 1000;

    string_size += std::snprintf(
        buffer + string_size, sizeof(buffer) - string_size,
        LOGGER_PRETTY_MS_FORMAT, ms
    );

    return std::string(buffer, buffer + string_size);
}
#包括
#包括
//strftime格式
#定义记录器时间格式“%Y-%m-%d%H:%m:%S”
//printf格式
#定义记录器\u PRETTY\u MS\u格式“%03d”
//将当前时间转换为unix纪元后的毫秒
模板
静态整数到毫秒(常数标准::时钟::时间点和tp)
{
使用名称空间std::chrono;
auto dur=tp.time_自_epoch()起;
返回静态施法(持续时间施法(dur.count());
}
//将其格式化为两部分:主要部分包含日期和时间,部分包含毫秒
静态std::string pretty_time()
{
自动tp=std::chrono::system_clock::now();
std::time\u t current\u time=std::chrono::system\u clock::to\u time\t(tp);
//此函数使用静态全局指针。因此它不是线程安全的解决方案
std::tm*time\u info=std::localtime(&当前时间);
字符缓冲区[128];
int string_size=strftime(
缓冲区,sizeof(缓冲区),
记录器\u PRETTY\u TIME\u格式,
时间信息
);
int-ms=to_-ms(tp)%1000;
字符串大小+=std::snprintf(
缓冲区+字符串大小,大小(缓冲区)-字符串大小,
LOGGER_PRETTY_MS_格式,MS
);
返回标准::字符串(缓冲区,缓冲区+字符串大小);
}
它以以下格式返回当前时间:
2018-09-23 21:58:52.642


是的,它需要
--std=c++11
或更高版本。

我通常使用我的实现来实现这些事情

#include <chrono>
#include <ctime>


// strftime format
#define LOGGER_PRETTY_TIME_FORMAT "%Y-%m-%d %H:%M:%S"

// printf format
#define LOGGER_PRETTY_MS_FORMAT ".%03d"


// convert current time to milliseconds since unix epoch
template <typename T>
static int to_ms(const std::chrono::time_point<T>& tp)
{
    using namespace std::chrono;

    auto dur = tp.time_since_epoch();
    return static_cast<int>(duration_cast<milliseconds>(dur).count());
}


// format it in two parts: main part with date and time and part with milliseconds
static std::string pretty_time()
{
    auto tp = std::chrono::system_clock::now();
    std::time_t current_time = std::chrono::system_clock::to_time_t(tp);

    // this function use static global pointer. so it is not thread safe solution
    std::tm* time_info = std::localtime(&current_time);

    char buffer[128];

    int string_size = strftime(
        buffer, sizeof(buffer),
        LOGGER_PRETTY_TIME_FORMAT,
        time_info
    );

    int ms = to_ms(tp) % 1000;

    string_size += std::snprintf(
        buffer + string_size, sizeof(buffer) - string_size,
        LOGGER_PRETTY_MS_FORMAT, ms
    );

    return std::string(buffer, buffer + string_size);
}
#包括
#包括
//strftime格式
#定义记录器时间格式“%Y-%m-%d%H:%m:%S”
//printf格式
#定义记录器\u PRETTY\u MS\u格式“%03d”
//将当前时间转换为unix纪元后的毫秒
模板
静态整数到毫秒(常数标准::时钟::时间点和tp)
{
使用名称空间std::chrono;
auto dur=tp.time_自_epoch()起;
返回静态施法(持续时间施法(dur.count());
}
//将其格式化为两部分:主要部分包含日期和时间,部分包含毫秒
静态std::string pretty_time()
{
自动tp=std::chrono::system_clock::now();
std::time\u t current\u time=std::chrono::system\u clock::to\u time\t(tp);
//此函数使用静态全局指针。因此它不是线程安全的解决方案
std::tm*time\u info=std::localtime(&当前时间);
字符缓冲区[128];
int string_size=strftime(
缓冲区,sizeof(缓冲区),
记录器\u PRETTY\u TIME\u格式,
时间信息
);
int-ms=to_-ms(tp)%1000;
字符串大小+=std::snprintf(
缓冲区+字符串大小,大小(缓冲区)-字符串大小,
LOGGER_PRETTY_MS_格式,MS
);
返回标准::字符串(缓冲区,缓冲区+字符串大小);
}
它以以下格式返回当前时间:
2018-09-23 21:58:52.642


是的,它需要
--std=c++11
或更高版本。

如果您想要更手动的方法,这是我以前使用过的方法

char buffer[MAX_BUFFER_SIZE];

time_t t = time(NULL);
struct tm *lt = localtime(&t);

snprintf(buffer, MAX_BUFFER_SIZE, "%02d/%02d/%02d %02d:%02d:%02d", lt->tm_mon+1, lt->tm_mday, lt->tm_year%100, lt->tm_hour, lt->tm_min, lt->tm_sec);

然后只需将缓冲区(现在包含时间的字符串表示)输出到您的文件。

如果您想要更手动的方法,这就是我以前使用的方法

char buffer[MAX_BUFFER_SIZE];

time_t t = time(NULL);
struct tm *lt = localtime(&t);

snprintf(buffer, MAX_BUFFER_SIZE, "%02d/%02d/%02d %02d:%02d:%02d", lt->tm_mon+1, lt->tm_mday, lt->tm_year%100, lt->tm_hour, lt->tm_min, lt->tm_sec);
然后只需将缓冲区(现在包含时间的字符串表示)输出到文件。

获取CPU时间戳 您需要使用
std::chrono::system_clock
来获取此时间戳。不要使用
std::chrono::stable_clock
std::chrono::high_resolution_clock
,因为它们是用于进行高精度定时测量的,并且不能保证对挂钟时间的保真度或准确性

auto now = std::chrono::system_clock::now();
//now is a time_point object describing the instant it was recorded according to your system clock
以可读格式打印此CPU时间戳 在C++20中,这非常简单

std::string formatted_time = std::format("{0:%F_%T}", now);
ofs << formatted_time << ": " << message << std::endl;
std::string formatted\u time=std::format(“{0:%F\u%T}”,现在);
ofs获取CPU时间戳
您需要使用
std::chrono::system_clock
来获取此时间戳。不要使用
std::chrono::stable_clock
std::chrono::high_resolution_clock
,因为它们是用于进行高精度定时测量的,并且不能保证对挂钟时间的保真度或准确性

auto now = std::chrono::system_clock::now();
//now is a time_point object describing the instant it was recorded according to your system clock
以可读格式打印此CPU时间戳 在C++20中,这非常简单

std::string formatted_time = std::format("{0:%F_%T}", now);
ofs << formatted_time << ": " << message << std::endl;
std::string formatted\u time=std::format(“{0:%F\u%T}”,现在);
ofs记录如下:

如果C++20功能不可用(如我的情况),则可以使用以下功能:

#include <ctime>
#include <iomanip>
#include <iostream>

using namespace std ;

time_t now = time(nullptr) ;
cout << put_time(localtime(&now), "%T") << endl ;
#包括
#包括
#包括
使用名称空间std;
time\u t now=时间(nullptr);
cout记录如下:

如果C++20功能不可用(如我的情况),则可以使用以下功能:

#include <ctime>
#include <iomanip>
#include <iostream>

using namespace std ;

time_t now = time(nullptr) ;
cout << put_time(localtime(&now), "%T") << endl ;
#包括
#包括
#包括
使用名称空间std;
time\u t now=时间(nullptr);

CUT是一个很好的开始的地方,直到它进入C++标准,如果你真的想对你的程序进行配置,为什么不使用为此设计的传统工具?注意:在使用日志文件之前先花点时间。你打开文件的时间等等…会影响你的结果。@ LeNNESSRACESIN轨道护理解释?W你确切地认为我知道你在说什么吗?@ USER481301谢谢你的提示!一个很棒的开始,直到它进入C++标准,如果你真的想对你的程序进行配置,为什么不使用为此设计的传统工具?注意:在使用日志文件之前先花点时间。g文件等…将影响您的结果。@LIghtnessRacesinOrbit不想解释吗?您如何确切地认为我知道您在说什么?@user4581301谢谢您的提示!谢谢您的回答。我如何才能告诉我们