C++ Log File Class
来源:互联网 发布:plc编程及应用第4版pdf 编辑:程序博客网 时间:2024/06/02 21:01
C++ can become verydifficult to use especially with large projects where you can't seeall the variables. Here's a very simple C++ logging class that can takelogs for your softwarewithout any effort. This will make you a better programmer as you won't have to rely ondebuggers like inMicrosoft's Visual Studio.
First you should create a project, with files like log.h and log.cpp. Let's show you the log.hfile:
using namespace std;
class Log {
};
I included fstream forofstream (which is anoutput file stream).
The logging class is called Log, it has one private (non-accessible variable bynon-class-members) member called m_stream which will be thefile stream to write ourlogs.
I have 3 functions, one constructor called Log, which takes achar pointer input filename, and a destructor ~Log to close ourfile and avoid memory leaks, and finally a void Write functionwhich will take a logline char pointer.
Here's the log.cpp file:
Log::Log(char*filename) {
}
void Log::Write(char*logline){
}
Log::~Log(){
}
I included the log.h, then defined the implementation for the 3functions.
The constructor will open the file delivered by filename on ourstream.
The Write function will take a string and write it to the logusing << operator, and will add a newline (endl) to the end of each call.
~Log the destructor will close the stream.
This really helps with debugging, so now I'll demonstrate how itcan be used in a project. Of course the code can be improved sothat you write less code in your main project.
#include<cstdlib>
int main(){
}
I created a Log class pointer, with the parameter "errors.log"which will be my error logs file.
I call Write to write a line of errors to my log.
If you need to include integers or other variable types, it maybe an idea to use sprintf to add the integer i to a char, which youcan then write to your log.
Variadic Functions
If you want to avoid using sprintf, and just using Write withva_list, or variadic argument lists:
Using the following modification to Write function, you cancreate a C++ variadicfunction. This should allow you to avoid using sprintf everytime.
void Log::Write(constchar* logline, ...){
}
- C++ Log File Class
- 关于log file sync事件
- NDK C打印log
- Can Not Allocate Log
- C++ static_cast
- Http bad file descriptor
- DB File Size limit
-  
- [ERROR] Failed to open log
- alter system archive current log…
- Objective C 监听 通知
- fzu 1759 A^B % C
-
- error: invalid storage class for…
- struct inode 和 struct file
- struct inode 和 struct file
- No simulation input file assignm…
- C standard library contents
- Linux常用命令学习
- [转]应该怎么读Linux?
- 机会成本
- 整理牛人看文献的方法
- [转]无线网络领域国际会议/期刊排…
- C++ Log File Class
- Linux下stricmp在此作用域中尚未声…
- 骑士信条
- Run Chinese CAJviewer by wine
- 一个大牛工程师的一些建议
- Power Measurement Units
- 一次“ERROR: OALL8 is in an inconsistent state”处理
- about srandom( time( NULL ))
- Ubuntu下deb与rpm包的安装方法