From 52d33a493af7f3d2e09588f81ba51298de752c4a Mon Sep 17 00:00:00 2001 From: Eric Cano <Eric.Cano@cern.ch> Date: Wed, 4 Apr 2018 11:05:10 +0200 Subject: [PATCH] Create util function to print out local time. --- common/utils/UtilsTest.cpp | 9 +++++++++ common/utils/utils.cpp | 17 +++++++++++++++++ common/utils/utils.hpp | 6 ++++++ 3 files changed, 32 insertions(+) diff --git a/common/utils/UtilsTest.cpp b/common/utils/UtilsTest.cpp index 93ba206767..14af7ec689 100644 --- a/common/utils/UtilsTest.cpp +++ b/common/utils/UtilsTest.cpp @@ -659,4 +659,13 @@ TEST_F(cta_UtilsTest, ellipses) { ASSERT_EQ("[...]0ABCDEF", preEllipsis("1234567890ABCDEF", 12)); } +TEST_F(cta_UtilsTest, DISABLED_currentTime) { + /* This test is disabled as it prints our similar, yet slightly different dates, + * so it would be complex to automate. + * Just run with: "cta-unitTests --gtest_filter=*currentTime --gtest_also_run_disabled_tests" */ + using namespace cta::utils; + ::system("date \"+%h %e %H:%M:%S.%N\" "); + std::cout << getCurrentLocalTime() << std::endl; +} + } // namespace unitTests diff --git a/common/utils/utils.cpp b/common/utils/utils.cpp index 95631e1447..6e74c4ac49 100644 --- a/common/utils/utils.cpp +++ b/common/utils/utils.cpp @@ -780,5 +780,22 @@ void copyString(char *const dst, const size_t dstSize, const std::string &src) { *(dst + dstSize -1) = '\0'; // Ensure destination string is null terminated } +//----------------------------------------------------------------------------- +// getCurrentLocalTime +//----------------------------------------------------------------------------- +std::string getCurrentLocalTime() { + ::timeval tv; + gettimeofday(&tv, nullptr); + time_t now = (time_t)tv.tv_sec; + struct tm * localNow; + ::time(&now); + localNow = ::localtime(&now); + char buff[80]; + char buff2[10]; + ::strftime(buff,sizeof(buff), "%b %e %H:%M:%S.", localNow); + ::snprintf(buff2, sizeof(buff2), "%06ld", tv.tv_usec); + return std::string(buff) + std::string(buff2); +} + } // namespace utils } // namespace cta diff --git a/common/utils/utils.hpp b/common/utils/utils.hpp index 37856789e7..c0334f867b 100644 --- a/common/utils/utils.hpp +++ b/common/utils/utils.hpp @@ -364,6 +364,12 @@ namespace utils { const std::string &src) { copyString(dst, dstSize, src); } + + /** + * Returns the current time, in the local time zone, formated for logging. + * @return the foramtted time. + */ + std::string getCurrentLocalTime(); } // namespace utils -- GitLab