简易c++版本日志库

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:....
}

原文链接: https://www.cnblogs.com/motadou/archive/2013/01/19/2867414.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    简易c++版本日志库

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/76099

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午5:20
下一篇 2023年2月9日 下午5:21

相关推荐