How do I write a message timestamp to a log file?

ekter15

I'm trying to create a logging file for my C++ program. My goal is to put two timestamps at two points of my program and print in a file the CPU time period between these two points. I'm doing this because I want to know which parts of my code are the most time consuming so I can make improvements (so there may be several chunks of code I want to measure). So far, I've made a function that, when called, prints a string that I pass as an argument, to a file:

#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();
}

However, I'm having difficulty figuring out how to print the CPU timestamp. Firstly, I don't know what time measurement format I should use (should I use the chrono or the time_t types?) I'm trying to print a time period so it would be helpful if there was a type for duration (I've tried chrono::duration but it seems to require C++11 support). Secondly, given I know what type to use, how do I print it to the file? Is there a way to cast that type to a string? Or can I pass it directly to my function and print it somehow?

This has troubled me a lot the last couple of days and I can't seem to figure it out, so any input would be really helpful. Thanks in advance!

Xirema

Get a CPU Timestamp

You'll want to use std::chrono::system_clock to get this timestamp. Do not use std::chrono::steady_clock or std::chrono::high_resolution_clock, as those are for making high-precision timing measurements, and do not guarantee fidelity or accuracy to wall-clock time.

auto now = std::chrono::system_clock::now();
//now is a time_point object describing the instant it was recorded according to your system clock

Print this CPU Timestamp in a readable format

In C++20, this is pretty trivial.

std::string formatted_time = std::chrono::format("%F_%T", now);
ofs << formatted_time << ": " << message << std::endl;
  • %F is a substitute for %Y-%m-%D, which will output year-month-day in ISO format, i.e. 2018-10-09.
  • %T is the same for %H:%M:%S, which will output a time, i.e. 17:55:34.786

See the specification for std::chrono::format for more options/details.

Prior to C++20

Consider Howard Hinnant's date library, most of which is being incorporated into C++20 as a new part of the chrono library. The format function found in that library uses the same syntax as suggested above for the C++20 version.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related