1 -- 簡易日誌庫
平時會寫些小的程式,需要打日誌,但又不想整個大的日誌庫,所以自己就寫個簡單點的,需要的時候就直接下載使用即可。
//將該檔案儲存為console.hpp#ifndef __CONSOLE_HPP__#define __CONSOLE_HPP__#include <stdio.h>#include <string>#include <stdarg.h>class console{public: static bool initialize(const std::string & path); static void log(char * format, ...); static void close();private: static FILE * _flogfile; static std::string _slogfile; static const std::string SLOGFILE;};FILE * console::_flogfile = NULL;std::string console::_slogfile = "";const std::string console::SLOGFILE = "/tmp/console.log";bool console::initialize(const std::string & path){ //已經開啟過,直接返回 if (_flogfile != NULL && (path == _slogfile || path == SLOGFILE)) { return true; } //目前已經開啟的非本次指定記錄檔 if (_flogfile != NULL) { fclose(_flogfile); _flogfile = NULL; } //開啟記錄檔 _slogfile = path; _flogfile = ::fopen(path.c_str(), "a+"); return _flogfile != NULL;}void console::close(){ ::fclose(_flogfile); _flogfile = NULL;}void console::log(char * format, ...){ initialize(SLOGFILE); if (_flogfile != NULL) { va_list arg_ptr; va_start(arg_ptr, format); vfprintf(_flogfile, format, arg_ptr); va_end(arg_ptr); fwrite("\n", 1, 1, _flogfile); fflush(_flogfile); }}#endif
2 -- 簡易日誌庫的使用方法
#include "console.hpp"int main(int argc, char ** argv){ //STEP01 需要在列印日誌之前,初始化日誌的存放地點。 // 如果不調用initialize進行初始化,那麼日誌的預設位置為:/tmp/console.log console::initialize("/home/motadou/main.log"); //STEP02 寫日誌到檔案 console::log("main.cpp::%d %s", argc, argv[0]); //TODO:....}