C++ 简单的日志类
2016-05-04 19:23
411 查看
/* 简单的日志记录类. (日志而已,何必那么复杂!!!) W.J.Chang 2013.12.13 说明:(EasyLog.h) 1, 简单的单件实现(自动垃圾回收) 2, 使用方法:EasyLog::Inst()->Log("Run..."); 3, 日志记录结果:Run... [2013.12.13 16:38:42 Friday] */ #pragma once #ifndef EASY_LOG_H_8080 #define EASY_LOG_H_8080 #include <memory> #include <ctime> #include <iostream> #include <fstream> class EasyLog { public: static EasyLog * Inst(){ if (0 == _instance.get()){ _instance.reset(new EasyLog); } return _instance.get(); } void Log(std::string msg); // 写日志的方法 private: EasyLog(void){} virtual ~EasyLog(void){} friend class std::auto_ptr<EasyLog>; static std::auto_ptr<EasyLog> _instance; }; std::auto_ptr<EasyLog> EasyLog::_instance; void EasyLog::Log(std::string loginfo) { std::ofstream ofs; time_t t = time(0); char tmp[64]; strftime(tmp, sizeof(tmp), "\t[%Y.%m.%d %X %A]", localtime(&t)); ofs.open("EasyLog.log", std::ofstream::app); ofs.write(loginfo.c_str(), loginfo.size()); ofs << tmp << '\n'; ofs.close(); } #endif
用法如下:
#include "EasyLog.h" int main() { EasyLog::Inst()->Log("Run..."); }
不只是main函数中,任何地方只要include头文件就可以用。
主要是辅助调试,特别是写dll程序的时候比较实用。可以加个宏控制。在发布的时候关掉日志功能。
#include "EasyLog.h" #define EASYLOG 1 int main(){ #if EASYLOG EasyLog::Inst()->Log("Run..."); #endif }
相关文章推荐
- poj3259(最短路)
- c语言中怎样用scanf()读入带空格的字符串
- c++ 之vector
- c++切割那个文件的代码
- PowerBuilder 调用C++ DLL方法
- 字符B中含有多少字符A C++||JAVA
- c,c++中const的用法
- C++结构体类型作为函数参数
- C语言中的__attribute__机制
- android studio 实现类似百度地图 发布SDK机制实现(jni实现调用C++的so库,并封装jar包)
- 正则表达式的使用(C++)
- C++ 在图片上打印文字并保存图片
- C++中虚析构函数的作用
- C++基础知识—常量和常成员函数
- C++转换构造函数和隐式转换函数
- Vulkan教程
- More Effective C++----(4)避免无用的缺省构造函数 & (5)谨慎定义类型转换函数
- C++11智能指针之unique_ptr
- C++11多线程编程 call_once
- C语言 文件操作11--文件函数再讲 fseek()和ftell()