如何用C ++编写日志文件
问题描述:
Hello all Programmer,
任何人都可以帮我用c ++编写日志文件或者为我提供指针或代码片段。
谢谢
Sampath
Hello all Programmer,
Can anybody help me to write log file in c++ or provide me the pointer or some code snippet for same.
thanks
Sampath
答
我会看到前面给出的C答案并提出一个C ++回答同样的事情:
I'll see the C answer given earlier and raise a C++ answer for the same thing:
#include <fstream>
void write_text_to_log_file( const std::string &text )
{
std::ofstream log_file(
"log_file.txt", std::ios_base::out | std::ios_base::app );
log_file << text << std::end;
}
如果文件由于某种原因无法打开,奖金也是如此在一堆未定义的行为中崩溃。
干杯,
Ash
PS当你自己写的时候记录的重要部分是:
- 每条消息后刷新 - std: :endl这样做
- 在每条消息后关闭文件 - fstream析构函数执行该操作
It'll do the same thing with the bonus that if the file fails to open for whatever reason it won't crash in a steaming heap of undefined behaviour.
Cheers,
Ash
PS the important bits of logging for when you write your own are:
- flush after every message - std::endl does that
- close the file after every message - the fstream destructor does that
您可以使用日志文件代码项目中存在的库
简单的LogFile [ ^ ]
you can use the log file library present in codeproject
A Simple LogFile[^]
日志文件基本上是一个文本文件。因此,您可以使用文件写入功能将日志写入其中。日志通常包含TimeStamp +错误代码+以及提及问题的小单行描述
log file is basically a text file. So you can use file writing functions to write logs on to it. Logs normally contains TimeStamp + Error Code + and a small single line description mentioning the problem