Skip to content

Commit

Permalink
fix path when roll files (#518)
Browse files Browse the repository at this point in the history
  • Loading branch information
qicosmos authored Dec 5, 2023
1 parent 9566c49 commit 2d637af
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
16 changes: 16 additions & 0 deletions include/ylt/easylog/appender.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include <shared_mutex>
#include <string>
#include <string_view>
#include <system_error>

#include "record.hpp"
#include "ylt/util/concurrentqueue.h"
Expand Down Expand Up @@ -303,6 +304,17 @@ class appender {
void open_log_file() {
file_size_ = 0;
std::string filename = build_filename();

if (std::filesystem::path(filename).has_parent_path()) {
std::error_code ec;
auto parant_path = std::filesystem::path(filename).parent_path();
std::filesystem::create_directories(parant_path, ec);
if (ec) {
std::cout << "create directories error: " << ec.message() << std::flush;
abort();
}
}

file_.open(filename, std::ios::binary | std::ios::out | std::ios::app);
if (file_) {
std::error_code ec;
Expand Down Expand Up @@ -338,6 +350,10 @@ class appender {
filename.append(file_path.extension().string());
}

if (std::filesystem::path(file_path).has_parent_path()) {
return file_path.parent_path().append(filename).string();
}

return filename;
}

Expand Down
21 changes: 21 additions & 0 deletions src/easylog/tests/test_easylog.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,27 @@ TEST_CASE("test basic") {
std::string::npos);
}

TEST_CASE("test roll files and automatic create directories") {
std::string filename = "a/b/c/test.txt";
std::filesystem::remove(filename);
CHECK(!std::filesystem::exists(filename));
constexpr size_t InstanceId = 888;
easylog::init_log<InstanceId>(Severity::DEBUG, filename, false, true, 20, 3,
true);
CHECK(std::filesystem::exists(filename));
MELOG_INFO(InstanceId) << 42 << " " << 4.5 << 'a' << " it is a test";
MELOG_INFO(InstanceId) << 42 << " " << 4.5 << 'a' << " it is a test";
MELOG_INFO(InstanceId) << 42 << " " << 4.5 << 'a' << " it is a test";

CHECK(std::filesystem::exists(filename));
CHECK(std::filesystem::exists("a/b/c/test.1.txt"));
CHECK(std::filesystem::exists("a/b/c/test.2.txt"));

std::error_code ec;
std::filesystem::remove_all("a", ec);
std::cout << ec.message() << "\n";
}

TEST_CASE("test_severity") {
// test severity
std::string severity_filename = "test_severity.txt";
Expand Down

0 comments on commit 2d637af

Please sign in to comment.