简单的C 日志打印函数


```cpp
#include <unistd.h>
#include <sys/types.h>

#include "ntylog.h"

FILE *nty_err_log = NULL;
#define NCPP_LOG_FILE "/home/nty.log"
#define NTY_LOG_SIZE 1*1024*1024*1024


struct _log_nty nty_logs = {
	.level = NTY_LOG_DEBUG,
};

//设置日志打印级别
int set_ntp_log_level(unsigned l){
	if(l > NTY_LOG_DEBUG)
		return -1;
	nty_logs.level = l;
	return 0;
} 
 
 
 
int nty_log(FILE *f, uint32_t level, const char *format, ...)
{
	long pos_curr;
	//打印级别大于设置级别返回
	if (level > nty_logs.level)
	{
		return 0;
	}
	va_list ap;
	int ret, fd;
	//2 1G以上的文件操作时可能出错。
	pos_curr = ftell(f);
	if(pos_curr > NTY_LOG_SIZE){
		fd = fileno(f);
		ftruncate(fd, 0);
		rewind(f);
	}	
	va_start(ap, format);
	ret = vfprintf(f, format, ap);
	fflush(f);
	va_end(ap);
	return ret;
}
 
int main(int argc, char* argv[])
{
	char * sbrk="sssddwadada";
	int daya=12345;
	nty_err_log = fopen(NCPP_LOG_FILE, "w+");
	if(!nty_err_log)
	{
		printf("ERR: Failed to open ncp log file.\n");
		return 0;
	}
	
	set_ntp_log_level(NTY_LOG_MAX);
	
	NTY_LOG(nty_err_log,ERR,"unit[%s]\n",sbrk);
	NTY_LOG(nty_err_log,WARN,"udss[%d]\n",daya);	
	fclose( nty_err_log );
	return 0;
}

```cpp
#ifndef __NTY_LOG_INC__
#define __NTY_LOG_INC__
#include "stdio.h"
#include "stdarg.h"
#include "stdint.h"

enum nty_log_l{
	NTY_LOG_EMERG = 1,
	NTY_LOG_ERR,
	NTY_LOG_WARN,
	NTY_LOG_INFO,
	NTY_LOG_DEBUG,
	NTY_LOG_MAX,
};

struct _log_nty{
	enum nty_log_l level;
};

int set_ntp_log_level(unsigned l);

int nty_log(FILE *f, uint32_t level, const char *format, ...);

#define NTYDEBUGBUILD
#ifdef NTYDEBUGBUILD
#define NTY_LOG(f, l, ...)					\
	 nty_log(f, NTY_LOG_ ## l, # l " : " __VA_ARGS__)
#else
#  define NTY_LOG(...)                                                          \
    do {                                                                       \
    } while (0)
#endif


	

	
#endif	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值