Linux C 自行搭建支持多线程的log系统_嵌入式linux下的c语言简易日志log模块

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

  • 26
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值