diff --git a/log4cpp.cpp b/log4cpp.cpp index 5779285..9581282 100644 --- a/log4cpp.cpp +++ b/log4cpp.cpp @@ -16,6 +16,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -29,16 +32,20 @@ mutex m; void print_timestamp() { + // retrieve accurate time for milliseconds display struct timeval secs; - (void)gettimeofday(&secs, NULL); - time_t now = time(NULL); - char dtstamp[32]; - strftime(dtstamp, 32, "%F %T", localtime(&now)); - long millisecs = (long)((double)secs.tv_usec / 1000.0 + 0.5) % 1000; + (void)::gettimeofday(&secs, nullptr); + int ms = static_cast(std::roundf(secs.tv_usec / 1000.0)) % 1000; + + // create a date/time stamp + char dtstamp[20]; + std::strftime(dtstamp, 20, "%F %T", std::localtime(&secs.tv_sec)); + + std::cerr << dtstamp << "." << std::setw(3) << ms << " "; #if __APPLE__ - fprintf(stderr, "%s.%03ld %s[%ld] ", dtstamp, millisecs, getprogname(), (long)getpid()); + std::cerr << getprogname() << "[" << getpid() << "] "; #elif __linux__ - fprintf(stderr, "%s.%03ld %s[%ld] ", dtstamp, millisecs, program_invocation_name, (long)getpid()); + std::cerr << program_invocation_name << "[" << getpid() << "] "; #endif } diff --git a/logger.cpp b/logger.cpp index 31a78c3..dcb0816 100644 --- a/logger.cpp +++ b/logger.cpp @@ -31,13 +31,13 @@ void logger::msg(loglevel level, const char* file, int line, const char* func) { void logger::write_prefix(loglevel level, const char* file, int line, const char* func) { // retrieve accurate time for milliseconds display - struct timeval secs; - (void)::gettimeofday(&secs, nullptr); - int ms = static_cast(std::roundf(secs.tv_usec / 1000.0)) % 1000; + struct timeval secs; + (void)::gettimeofday(&secs, nullptr); + int ms = static_cast(std::roundf(secs.tv_usec / 1000.0)) % 1000; // create a date/time stamp - char dtstamp[20]; - std::strftime(dtstamp, 20, "%F %T", std::localtime(&secs.tv_sec)); + char dtstamp[20]; + std::strftime(dtstamp, 20, "%F %T", std::localtime(&secs.tv_sec)); std::cerr << dtstamp << "." << std::setw(3) << ms << " "; std::cerr << _name << "[" << ::getpid() << "] ";