Add thread safe function for server time logging prefix

This commit is contained in:
Benau 2020-02-25 12:17:27 +08:00
parent 40c57e8115
commit a418302d9f
3 changed files with 25 additions and 2 deletions

View File

@ -165,9 +165,8 @@ void Log::printMessage(int level, const char *component, const char *format,
if (NetworkConfig::get()->isNetworking() &&
NetworkConfig::get()->isServer())
{
std::time_t result = std::time(nullptr);
index += snprintf (line + index, remaining,
"%.24s [%s] %s: ", std::asctime(std::localtime(&result)),
"%s [%s] %s: ", StkTime::getLogTime().c_str(),
names[level], component);
}
else

View File

@ -42,6 +42,26 @@ void StkTime::init()
m_timer->grab();
} // init
// ----------------------------------------------------------------------------
/** Get the time in string for game server logging prefix (thread-safe)*/
std::string StkTime::getLogTime()
{
time_t time_now = 0;
time(&time_now);
std::tm timeptr = {};
#ifdef WIN32
localtime_s(&timeptr, &time_now);
#else
localtime_r(&time_now, &timeptr);
#endif
std::string result;
result.resize(64);
strftime(&result[0], 64, "%a %b %d %H:%M:%S %Y", &timeptr);
size_t len = strlen(result.c_str());
result.resize(len);
return result;
} // getLogTime
// ----------------------------------------------------------------------------
/** Converts the time in this object to a human readable string. */

View File

@ -55,6 +55,10 @@ public:
static void init();
static void getDate(int *day=NULL, int *month=NULL, int *year=NULL);
// ------------------------------------------------------------------------
/** Get the time in string for game server logging prefix (thread-safe)*/
static std::string getLogTime();
// ------------------------------------------------------------------------
/** Converts the time in this object to a human readable string. */
static std::string toString(const TimeType &tt);
// ------------------------------------------------------------------------