日志文件中的日期使用 ofstream
Date in log file using ofstream
下面是我每次想在日志文件中包含日期时必须编写的代码。我正在寻找一种方法,不必每次想在文件中写入内容时都不必写我的CurrentDateToString()
。
ofstream log;
log.open("test.log", ios_base::app);
log << CurrentDateToString() << " | " << "first line" << endl;
log << CurrentDateToString() << " | " << "second line" << endl;
log.close();
这是我的CurrentDateToString()
函数:
// convert date to formatted string
string CurrentDateToString()
{
time_t rawtime;
struct tm* timeInfo;
char buffer[80];
time(&rawtime);
timeInfo = localtime(&rawtime);
strftime(buffer, 80, "%Y-%m-%d %I:%M:%S", timeInfo);
string dateString(buffer);
return dateString;
}
这里的目标是能够写这些行,而不是我正在写的当前行:
log << "first line" << endl;
log << "second line" << endl;
我是否必须编写日志类和重载运算符<<或者有其他方法可以做到这一点?
实现自动添加(或删除)字符(例如添加日期)的流的方法是创建一个过滤流缓冲区。您将从std::streambuf
派生一个类,该类将收到的字符调整为必要的形式,然后将它们转发到基础流缓冲区。
对于在行首添加日期的使用,您只需观察收到的换行符,并在need_date
有换行符时设置标志。在设置字符时写入字符need_date
时,将写入日期并清除标志。
以下是寻找您的约会对象的方法:
#include <streambuf>
class logbuf
: public std::streambuf {
std::streambuf* sbuf;
bool need_date{true};
using traits_type = std::char_traits<char>;
int overflow(int c) override {
if (c != traits_type::eof()) {
if (need_date) {
std::string date{CurrentDateToString()};
this->sbuf->sputn(date.c_str(), date.size());
need_date = false;
}
if (c == 'n') {
need_date = true;
}
return this->sbuf->sputc(c);
}
else {
return traits_type::not_eof(c);
}
}
int sync() override { return this->sbuf->pubsync(); }
public:
logbuf(std::streambuf* sbuf): sbuf(sbuf) {}
};
每次流缓冲区的缓冲区中没有空间时,都会调用 virtual
函数 overflow()
。由于没有为每个字符设置输出缓冲区(可以通过添加xsputn()
覆盖和/或添加缓冲来提高性能)。每次刷新流时都会调用函数 sync()
。由于没有缓冲任何内容,因此刷新请求只是转发到基础流缓冲区。
下面是使用此流缓冲区的简单演示。创建一个合适的底层流缓冲区,例如,一个std::filebuf
,和一个std::ostream
可以打包到一个派生自std::ostream
的类中。
#include <iostream>
int main()
{
logbuf sbuf(std::cout.rdbuf());
std::ostream logout(&sbuf);
logout << "hellonwordln";
logout << "n";
logout << "goodbyen";
}
相关文章:
- 查询SQLite数据库中的日期
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- Log4cpp:以UTC/GMT时区打印日期
- 使用C++的日期库读取时间
- 日期格式为C++
- 如何在 C++20 计时中为日期添加天数?
- std::ofstream 作为类成员删除复制构造函数?
- 如何在QTableView中排序和更改日期格式
- 如何在cpp中使用地图显示给定日期范围内(在下面的问题中)的费率?
- Gtkmm 会不断检查 Gtk::日历上的所选日期是否发生变化
- ofstream::close() 是否在 Linux 上调用同步?
- fmt 与 Howard Hinnant 的日期:为什么从 fmt::to_string "{}"?FMT 和日期的最佳实践?
- 使程序检查当前日期是否=预期日期
- 如何在软件代码中使用ofstream创建文件
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- JNI 日期值转换问题,在C++中获取不同的长整型值
- Ofstream和IFSTREAM有什么区别?
- 使用 libssh 从 SFTP 服务器下载文件并使用 C++ 将其写入 ofstream?
- 确定夏令时是否适用于特定日期
- 日志文件中的日期使用 ofstream