linux c 日志写入文件,linux下C语言实现写日志功能

先上程序,该程序经过测试能够很好的实现写日志要求/************************************************************************* > File Name: log.c > Author: ************************************************************************/#include #include #include #include #include #include #include #include #include int safe_asprintf(char **strp, const char *fmt, ...);int safe_vasprintf(char **strp, const char *fmt, va_list ap);void plog(const char *format, ...) ;void pinfo(const char *format, ...) ;#define DEBUG#ifdef DEBUGvoid plog(const char *format, ...);void pinfo(const char *format, ...);#define debug(fmt, args...) plog(fmt, ##args) #else#define debug(fmt, args...) do{}while(0)#endifstatic pthread_mutex_t fileMutex = PTHREAD_MUTEX_INITIALIZER;int main(int argc, char *argv){ return 0;}/* * safe_asprintf(); */int safe_asprintf(char **strp, const char *fmt, ...) { va_list ap; int retval; va_start(ap, fmt); retval = safe_vasprintf(strp, fmt, ap); va_end(ap); return retval;}/* * safe_vasprintf(); */int safe_vasprintf(char **strp, const char *fmt, va_list ap) { int retval; retval = vasprintf(strp, fmt, ap); if (retval == -1) { printf("Failed to vasprintf: %s. Bailing out", strerror(errno)); return 1; } return retval;}/* * plog(); */void plog(const char *format, ...) { pthread_mutex_lock(&fileMutex); FILE *fp = NULL; va_list vlist; char *fmt = NULL; // Open debug info output file. if (!(fp = fopen("log.txt", "a+"))) { pthread_mutex_unlock(&fileMutex); return; } va_start(vlist, format); safe_vasprintf(&fmt, format, vlist); va_end(vlist); if (!fmt) { pthread_mutex_unlock(&fileMutex); return; } time_t timep; struct tm *ptm = NULL; time(&timep); ptm = localtime(&timep); fprintf(fp, "[%04d-%02d-%02d-%02d-%02d-%02d] %s", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec, fmt); free(fmt); fsync(fileno(fp)); fclose(fp); pthread_mutex_unlock(&fileMutex);}/* * pinfo(); */void pinfo(const char *format, ...) { pthread_mutex_lock(&fileMutex); FILE *fp = NULL; va_list vlist; char *fmt = NULL; // Open debug info output file. if (!(fp = fopen("log.txt", "a+"))) { pthread_mutex_unlock(&fileMutex); return; } va_start(vlist, format); safe_vasprintf(&fmt, format, vlist); va_end(vlist); if (!fmt) { pthread_mutex_unlock(&fileMutex); return; } fprintf(fp, "%s", fmt); free(fmt); fsync(fileno(fp)); fclose(fp); pthread_mutex_unlock(&fileMutex);}

程序实现的日志格式为:

时间 + 空格 + 具体实现(自己的调试内容)

本段程序值得学习的地方:va_list 结构体的使用

linux 的格式化输出字符串

文件操作过程中pthread_mutex锁的使用,以及他的优点

linux DEBUG 的应用,方便调试

linux如何查看日志:

使用tail 命令可以实现日志的查询,以及其他功能,不了解的话,自行查资料解决。

对上面应用不明白的请自行查资料解决。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值