int millsec;
t = time(NULL);
p = localtime(&t);
gettimeofday(&tv, NULL);
millsec = (int)(tv.tv_usec / 1000);
/* 时间格式:2011-11-15 12:47:34:888 */
len = snprintf(buffer, 32, "%04d-%02d-%02d %02d:%02d:%02d:%03d ",\
p->tm_year+1900, p->tm_mon+1,\
p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec, millsec);
buffer[len] = '\0';
}
static inline int log_print_args(int prio, ConstCharPtr tag, ConstCharPtr fmt, va_list vargs)
{
int count = 0;
static char *prioNames[] = {“”, “D”, “I”, “W”, “E”, “F”, “S”};
char timeStr[64] = {0};
get_timestamp(timeStr);
count = fprintf(stderr, "%s %7d %7ld %3s %7s ", timeStr, getpid(), gettid(), prioNames[prio], tag);
if (count < 0) {
return 0;
}
count = count + vfprintf(stderr, fmt, vargs) + fprintf(stderr, "\n");
fflush(stderr);
return count;
}
int inline LOG_PRINT(int prio, ConstCharPtr tag, ConstCharPtr fmt, …)
{
va_list vargs;
va_start(vargs, fmt);
int count = log_print_args(prio, tag, fmt, vargs);
va_end(vargs);
return count;
}
### log系统线程安全
wirte函数在O_APPEND模式下,是线程安全的。所以使用线程读写锁,让写日志函数多并发运行。定时进入写模式刷新数据,并通过判断文件大小进行压缩备份。
#### 初始化线程锁
![初始化线程锁](https://img-blog.csdnimg.cn/direct/6bf1a05c389d488e888b5184707320f8.png)
#### 写 log
![写安全](https://img-blog.csdnimg.cn/direct/d26e4384edc34829a5669a58ef61e053.png)
#### 压缩文件
![压缩文件](https://img-blog.csdnimg.cn/direct/86df3ef59a644861b9f5ecdf59c861f4.png)
/* thread control