簡易C++版本日誌庫

來源:互聯網
上載者:User
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:....}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.