user987316
user987316

Reputation: 942

Create a file which can be renamed while in use

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);

Upvotes: 0

Views: 801

Answers (2)

stamhaney
stamhaney

Reputation: 1314

You can achieve this by synchronizing access to the Log class object. An approach could be as follows:

  1. Application creates the Log class object on startup Create a Synchronization object (say Mutex) which protects access to the Logging
  2. Have the Log method accept a flag which will differentiate between accesses from two different modules
  3. Module1 gains access and starts logging
  4. When module2 wants to write, the Logger will detect that it has a Log request from another module, and will close the file and then rename it and create another log file with the same name

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

Windows does not allow this. When you open a file, for writing or for reading, it's locked and you can't do operations such as rename or delete while the file is open.

You might want to reconsider your design. Either so that each submodule have its own uniquely named log file. Or use a logging module that can receive logging input from multiple sources and multiplex those into a single file.

Upvotes: 2

Related Questions