如何在c中为日志获取适当的时间戳?

use*_*772 9 c logging timestamp

我正在创建一个客户端 - 服务器应用程序.我想做一些日志记录.

服务器在C中.现在我打印到终端的消息.所以我可能只是将其复制到sprintf并添加时间戳.我该怎么做那个时间戳?它应该包括日期,小时,分钟,秒.

Pav*_*ath 17

#include <time.h>
void timestamp()
{
    time_t ltime; /* calendar time */
    ltime=time(NULL); /* get current cal time */
    printf("%s",asctime( localtime(&ltime) ) );
}
Run Code Online (Sandbox Code Playgroud)

在我的电脑上,它只是打印

Wed Mar 07 12:27:29 2012
Run Code Online (Sandbox Code Playgroud)

查看全部时间相关功能 http://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html


Jay*_*Jay 5

请在下面找到Pavan的答案的线程安全版本.

time_t ltime;
struct tm result;
char stime[32];

ltime = time(NULL);
localtime_r(&ltime, &result);
asctime_r(&result, stime);
Run Code Online (Sandbox Code Playgroud)

请参考了解更多详情.