一个简易的打log的c代码

log.h 

#ifndef _log_h__
#define _log_h__

#define LEVEL_DEBUG    0
#define LEVEL_TUNNINT  1
#define LEVEL_INFO     2
#define LEVEL_WARN     3
#define LEVEL_ERROR    4

#define TRACE_INFO(...)      trace(LEVEL_INFO,  __VA_ARGS__);
#define TRACE_DEBUG(...)     trace(LEVEL_DEBUG, __VA_ARGS__);
#define TRACE_ERROR(...)     trace(LEVEL_ERROR, __VA_ARGS__);

void set_log_path(const char* path);

void trace(int log_level, const char* format, ...);

#endif

log.c


#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
#include<stdarg.h>
#include<unistd.h>
#include<sys/stat.h>

#include "log.h"

static const char* _log_path = NULL;

static const char* llchar = "DTIWEFM";

void set_log_path(const char* path) {
	_log_path = path;
}

static const char* get_log_path() {
	return _log_path;
}

static void mkdir_for_log(const char* log_path, int mode) {
	if (NULL == log_path)
		return;
	char* path = strdup(log_path);
	char* p = strrchr(path, '/');
	if (p) *p = '\0';

	if (0 != access(path, 0)) {
		p = path;
		do {
			p = strchr(p + 1, '/');
			if (p) *p = '\0';
			if (0 != access(path, 0))
				mkdir(path, mode);
			if (p) *p = '/';
		} while(p);
	} 
	free(path);
}

static void write_file(const char* log_path, char* message) {
	FILE *fp = fopen(log_path, "a");
	if (fp) {
		chmod(log_path, 0755);
		strcat(message, "\n");
		int len = strlen(message);
		fwrite(message, len, 1, fp);
		fclose(fp);
	}
}

static void log_header(int log_level, char* message) {
	time_t t = {0};
	time(&t);
	struct tm* p = localtime(&t);
	sprintf(message, "%d-%c %2d-%2d %2d:%2d:%2d ", getpid(), llchar[log_level], p->tm_mon+1, p->tm_mday,
			p->tm_hour, p->tm_min, p->tm_sec);
}

void trace(int log_level, const char* format, ...) {
	va_list ap;
	char message[1024];
	if (NULL == format)
		return;
	log_header(log_level, message);
	int len = strlen(message);
	va_start(ap, format);
	vsnprintf(message + len, sizeof(message) - len - 2, format, ap);
	va_end(ap);
	mkdir_for_log(get_log_path(), 0700);
	write_file(get_log_path(), message);
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值