emilk / loguru

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

Windows logging to file on different drive fails #238

Closed pn2200 closed 11 months ago

pn2200 commented 1 year ago

On Windows, when logging to a file on a different drive, where the file and the directory do not exist, fails. Logs are not written to the file, the log file is not created, and the directory is not created. The following is the output from the reproducer program.

date       time         ( uptime  ) [ thread name/id ]                   file:line     v|
2023-05-03 15:14:38.455 (   0.058s) [main thread     ]             loguru.cpp:659   INFO| arguments: C:\\Users\\pnova\\loguru\\loguru_repro\\x64\\Debug\\loguru_repro.exe
2023-05-03 15:14:38.459 (   0.059s) [main thread     ]             loguru.cpp:662   INFO| Current dir: C:\Users\pnova\loguru\loguru_repro\loguru_repro
2023-05-03 15:14:38.459 (   0.059s) [main thread     ]             loguru.cpp:664   INFO| stderr verbosity: 0
2023-05-03 15:14:38.459 (   0.059s) [main thread     ]             loguru.cpp:665   INFO| -----------------------------------
2023-05-03 15:14:38.459 (   0.059s) [main thread     ]             loguru.cpp:809    ERR| Failed to open 'D:\logs\everything.log'
2023-05-03 15:14:38.459 (   0.059s) [main thread     ]       loguru_repro.cpp:13     ERR| Log something
2023-05-03 15:14:38.459 (   0.059s) [main thread     ]             loguru.cpp:538   INFO| atexit

Reproducer:

#include "loguru.hpp"

int main(int argc, char **argv)
{
    loguru::init(argc, argv);

    // D: drive exists, but D:\logs\everything.log does not exist:
    loguru::add_file("D:\\logs\\everything.log", loguru::Append, loguru::Verbosity_MAX);

    LOG_F(ERROR, "Log something");
}
BullyWiiPlaza commented 1 year ago

The issue is rather that the parent folder is not created when it doesn't exist. Make sure to create it yourself then:

// D: drive exists, but D:\logs\everything.log does not exist:
std::filesystem::path log_file_path = "D:\\logs\\everything.log";
std::filesystem::create_directories(log_file_path.parent_path());
const auto log_file_path_string = log_file_path.string();
loguru::add_file(log_file_path_string.c_str(), loguru::Append, loguru::Verbosity_MAX);

LOG_F(ERROR, "Log something");

I agree however that it would be great if loguru handled this correctly by itself internally. However, it's quite a C mess.

pn2200 commented 11 months ago

Ah, my mistake, thanks for the response. Closing issue.