一个简单的log用c++编写

#ifndef __debug_log__
#define __debug_log__

//#define __WRITE_FILE__

#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdarg.h>

void DEBUG_LOG(const char *msg, ...);

class Debug_LOG {
private:
	Debug_LOG();
	~Debug_LOG();
	void create_log_file();
public:
	static Debug_LOG *log();
	void write_log(const char *msg);
private:
	static Debug_LOG *m_log;
	time_t tim;
	struct tm *t;
	FILE *fp;
	char filepath[32];
	char message[256];
	struct tm last_log_time;
};

#endif
#include "stdafx.h"
#include "debug_log.h"
#include <winbase.h>

void DEBUG_LOG(const char *msg, ...) {
	//char message[4096] = {0};
	//va_list args;
	//va_start(args, msg);
	//vsprintf(message, msg, args);
	//va_end(args);
	//Debug_LOG::log()->write_log(message);
}

Debug_LOG *Debug_LOG::m_log = NULL;

Debug_LOG::Debug_LOG():
	tim(0),
	t(NULL),
	fp(NULL),
	filepath(),
	message(),
	last_log_time()
{
#ifdef __WRITE_FILE__
	create_log_file();
#endif
}

Debug_LOG::~Debug_LOG(){
#ifdef __WRITE_FILE__
	fclose(fp);
#endif
}

void Debug_LOG::create_log_file(){
	if(fp != NULL)
		fclose(fp);

	sprintf(filepath, "./log/debuglog_");
	time(&tim); 
	t = localtime(&tim);
	memcpy(&last_log_time, t, sizeof(struct tm));
	sprintf(filepath + 15, "%02d_%02d",t->tm_mon + 1, t->tm_mday); 
	fp = fopen(filepath, "a+");
}

Debug_LOG *Debug_LOG::log(){
	if(m_log == NULL){
		m_log = new Debug_LOG();
	}
	return m_log;
}

void Debug_LOG::write_log(const char *msg){
	time(&tim); 
	t = localtime(&tim); 
	sprintf(message, "[%02d:%02d:%02d] %s\n", t->tm_hour, t->tm_min, t->tm_sec, msg);
#ifdef __WRITE_FILE__
	if(t->tm_mday != last_log_time.tm_mday || t->tm_mon != last_log_time.tm_mon
		|| t->tm_year != last_log_time.tm_year)
		create_log_file();
	fwrite(message, strlen(message), 1, fp);
	fflush(fp);
#else
	printf("\n%s", message);
	OutputDebugString(message);
	fflush(stdout);
#endif
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值