From 0d4bb3ffb03f43f889fa3cab18ae6dfe390b87b3 Mon Sep 17 00:00:00 2001 From: qicosmos Date: Tue, 5 Dec 2023 17:24:27 +0800 Subject: [PATCH] fix path when roll files --- include/ylt/easylog/appender.hpp | 16 ++++++++++++++++ src/easylog/tests/test_easylog.cpp | 21 +++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/include/ylt/easylog/appender.hpp b/include/ylt/easylog/appender.hpp index 70c7fcf0d..9118bd774 100644 --- a/include/ylt/easylog/appender.hpp +++ b/include/ylt/easylog/appender.hpp @@ -22,6 +22,7 @@ #include #include #include +#include #include "record.hpp" #include "ylt/util/concurrentqueue.h" @@ -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; @@ -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; } diff --git a/src/easylog/tests/test_easylog.cpp b/src/easylog/tests/test_easylog.cpp index 43b69e344..fb41261b9 100644 --- a/src/easylog/tests/test_easylog.cpp +++ b/src/easylog/tests/test_easylog.cpp @@ -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(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";