改进log4c的时间戳结构:
log4c里对于事件时间戳的定义是这样的:
1 #ifndef _WIN32
2 struct timeval evt_timestamp;
3 #else
4 FILETIME evt_timestamp;
5 #endif
这个不用说是很恶了,存的是各个平台的api得到的原始时间,格式化的时候还要按不同平台写不同的格式化代码,而我们输出日志的时候通常是按年月日时分秒的结构来输出,存一个通用的结构更好,time.h里就有一个比较好的结构struct tm, 可以使用gmtime或localtime来得到。
1 struct tm {
2 int tm_sec; /* seconds after the minute - [0,59] */
3 int tm_min; /* minutes after the hour - [0,59] */
4 int tm_hour; /* hours since midnight - [0,23] */
5 int tm_mday; /* day of the month - [1,31] */
6 int tm_mon; /* months since January - [0,11] */
7 int tm_year; /* years since 1900 */
8 int tm_wday; /* days since Sunday - [0,6] */
9 int tm_yday; /* days since January 1 - [0,365] */
10 int tm_isdst; /* daylight savings time flag */
11 };
时间精确到秒,而且可惜的是,这些函数的跨平台性不够好,windows ce上就没有,所以定义一个通用的时间结构如下:
1 typedef struct
2 {
3 int tm_milli; /* millisecond - [0,999] */
4 int tm_sec; /* seconds after the minute - [0,59] */
5 int tm_min; /* minutes after the hour - [0,59] */
6 int tm_hour; /* hours since midnight - [0,23] */
7 int tm_mday; /* day of the month - [1,31] */
8 int tm_mon; /* months since January - [0,11] */
9 int tm_year; /* years since 1900 */
10 int tm_wday; /* days since Sunday - [0,6] */
11 int tm_yday; /* days since January 1 - [0,365] */
12 } log4c_common_time_t;
跟struct tm相比,增加了一个
tm_milli,因为依赖平台相关api的话,可以取到更精确的时间。这样输出的时候把它的fields格式化就可以了。
接下来就是取当前时间戳的函数来,跟平台相关,支持struct tm,localtime的版本如下,精度为秒:
1 void xp_gettimeofday(log4c_common_time_t* p,void* reserve)
2 {
3 struct tm tm;
4 time_t t = time(0);
5 tm = *localtime(&t);
6
7 p->tm_hour = tm.tm_hour;
8 p->tm_isdst = tm.tm_isdst;
9 p->tm_mday = tm.tm_mday;
10 p->tm_milli = 0;
11 p->tm_min = tm.tm_min;
12 p->tm_mon = tm.tm_mon;
13 p->tm_sec = tm.tm_sec;
14 p->tm_wday = tm.tm_wday;
15 p->tm_yday = tm.tm_yday;
16 p->tm_year = tm.tm_year + 1900;
17 }
Windows CE使用的版本如下,精度为毫秒,当然windows也可以使用:
1 void xp_gettimeofday(log4c_common_time_t* p)
2 {
3 SYSTEMTIME time;
4 GetSystemTime(&time);
5 p->tm_milli = time.wMilliseconds;
6 p->tm_sec = time.wSecond;
7 p->tm_min = time.wMinute;
8 p->tm_hour = time.wHour;
9 p->tm_mday = time.wDay;
10 p->tm_mon = time.wMonth;
11 p->tm_wday = time.wDayOfWeek;
12 p->tm_year = time.wYear;
13 }