emilk / loguru

A lightweight C++ logging library
The Unlicense
1.77k stars 256 forks source link

Unable to have a log rotation on windows because of the current architecture #147

Open Milerius opened 4 years ago

Milerius commented 4 years ago

It is currently impossible on windows to make your own log rotation system because to do this you would first have to close the file, then move it under another name, and then reopen the file with the old name.

None of its functions are exposed in loguru.hpp.

However, according to some issues, it is stated that here, that a simple file renaming would automatically reopen the file with LOGURU_FILEABS.

This is wrong, because on Windows you cannot move a file that is still open, you will get a message (This file is currently used by another process).

One solution could be to offer a function that allows you to close the current stream, and then rename the file under another name.

I saw that there is a file_close function exposed in Loguru.cpp which takes a user_data, but it seems to be very internal and unusable from the outside.

For example this code snippet will never work on Windows if we cannot close the file before :

 if (fs::exists(current_log_file))
        {
            if (auto f_size = fs::file_size(current_log_file); f_size > 7777777)
            {
                if (fs::exists(current_log_file.string() + ".old"))
                {
                    fs::remove(current_log_file.string() + ".old");
                }

                boost::system::error_code ec;

                fs::rename(current_log_file, current_log_file.string() + ".old", ec);

                if (ec)
                {
                    std::cerr << ec.message() << std::endl;
                    LOG_F(WARNING, "Log rotation failed {}", ec.message());
                }
                else
                {
                    LOG_F(INFO, "Log rotation finished, previous file size: {}", f_size);
                }
            }
        }