首页
社区
课程
招聘
[原创]发些个人库之 log 信息输出
发表于: 2013-10-7 12:54 4262

[原创]发些个人库之 log 信息输出

2013-10-7 12:54
4262
鉴于某某发了一份Logger代码,我也来发一份自己的logger简单版本(需要功能自己扩展,以下代码我只用到了这些功能),写的很烂,还望被批斗。
用法:
base::tsLogger::run().Format(base::tsLogger::DEBUG,"%s",var)

tsLogger.h
/*
 * tsLogger.h
 *
 *  Created on: Oct 4, 2013
 *      Author: vscen
 */

#ifndef TSLOGGER_H_
#define TSLOGGER_H_

#include "xxxxxx.h"

namespace base {
class tsLogger {
	static pthread_mutex_t lock_;
	std::ofstream stream_;
public:
	enum Level{DEBUG,INFO,ERROR};
public:
	tsLogger();
	~tsLogger();
	static tsLogger& Run();
	inline static void lock();
	inline static void unlock();
	void Format(Level level,const char* format, ...);
private:
	void FmtLevel(Level level);
};
}

#endif /* TSLOGGER_H_ */


tsLogger.cc
/*
 * tsLogger.cc
 *
 *  Created on: Oct 4, 2013
 *      Author: vscen
 */

#include "tsLogger.h"

namespace base {
pthread_mutex_t tsLogger::lock_ = PTHREAD_MUTEX_INITIALIZER;
tsLogger instance_;
tsLogger::tsLogger() {
	tsLogger::stream_.open("linuxvw.log", std::ofstream::out
			| std::ofstream::app);
	pthread_mutex_init(&lock_, NULL);
}

tsLogger::~tsLogger() {
	if (tsLogger::stream_.is_open()) {
		tsLogger::stream_.close();
	}
	pthread_mutex_destroy(&lock_);
}

tsLogger& tsLogger::Run() {
	return instance_;
}

inline void tsLogger::lock() {
	pthread_mutex_lock(&lock_);
}

inline void tsLogger::unlock() {
	pthread_mutex_unlock(&lock_);
}

void tsLogger::Format(Level level, const char* format, ...) {
	va_list argList;
	char cbuffer[kMaxFmtMessage] = { 0 };
        tsLogger::lock();
	va_start(argList, format);
	vsnprintf(cbuffer, kMaxFmtMessage, format, argList);
	va_end(argList);
	tsLogger::FmtLevel(level);
	tsLogger::stream_ << cbuffer << std::endl;
        tsLogger::unlock();
}

void tsLogger::FmtLevel(Level level) {
	switch(level)
	{
	case DEBUG:
		tsLogger::stream_ << "[DEBUG]:";
		break;
	case INFO:
		tsLogger::stream_ << "[INFO]:";
		break;
	case ERROR:
		tsLogger::stream_ << "[ERROR]:";
		break;
	default:
		break;
	}
}
}

[课程]Linux pwn 探索篇!

收藏
免费 5
支持
分享
最新回复 (0)
游客
登录 | 注册 方可回帖
返回
//