0

I have a application which has two sub modules. Also their is custom Log class written to log module activities.Requirement I am working on is each module should create log file with same name and write log into that. To explain it better consider initial run in which module1 is wrting logs in app.log now when another session of application starts with module2 it should also create app.log and start writing. but before that old app.log should get rename to something app.log.1.

Issue I am facing when log file is open with one module function fails to rename. I am working in C++ on window 7. To create a file I am using - std::ofstream s_ofs.open("app.log", std::ios::out | std::ios::app);

4

2 回答 2

2

Windows 不允许这样做。当你打开一个文件,写入读取时,它被锁定,你不能在文件打开时进行重命名或删除等操作。

您可能需要重新考虑您的设计。要么让每个子模块都有自己唯一命名的日志文件。或者使用一个日志模块,它可以接收来自多个源的日志输入并将它们多路复用到一个文件中。

于 2013-11-13T08:28:46.550 回答
1

您可以通过同步对 Log 类对象的访问来实现这一点。一种方法可能如下:

  1. 应用程序在启动时创建 Log 类对象 创建一个同步对象(比如 Mutex),以保护对 Logging 的访问
  2. 让 Log 方法接受一个标志,该标志将区分来自两个不同模块的访问
  3. Module1 获得访问权限并开始记录
  4. 当module2要写的时候,Logger会检测到有另一个模块的Log请求,会关闭文件然后重命名,再创建一个同名的日志文件
于 2013-11-13T08:55:11.503 回答