Compare commits

...

13 Commits

32 changed files with 4130 additions and 259 deletions
+12
View File
@@ -1,4 +1,16 @@
# Generated documentation
docs/
# Logs
*.log
# Cache directories
.cache/
# ---> C++ # ---> C++
# compilation database
compile_commands.json
# Prerequisites # Prerequisites
*.d *.d
+15
View File
@@ -0,0 +1,15 @@
FROM ubuntu:24.04
RUN apt update && apt install -y \
build-essential \
cmake \
gdb \
valgrind \
git \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /project
COPY . .
CMD ["bash"]
+3043
View File
File diff suppressed because it is too large Load Diff
+18 -6
View File
@@ -1,22 +1,34 @@
export ROOT_DIR := $(CURDIR)
export BUILD_DIR := $(ROOT_DIR)/build
export CC := gcc
export CXXFLAGS := \
-std=c++17 \
-Wall \
-Wextra \
-Werror
export LDLIBS := -lstdc++
.PHONY: all logger app tests clean .PHONY: all logger app tests clean
all: logger app tests all: logger app tests
logger: logger:
$(MAKE) -C logger $(MAKE) -C logger
app: logger app: logger
$(MAKE) -C app $(MAKE) -C app
tests:
tests: logger
$(MAKE) -C tests $(MAKE) -C tests
clean: clean:
$(MAKE) -C logger clean $(MAKE) -C logger clean
$(MAKE) -C app clean $(MAKE) -C app clean
$(MAKE) -C tests clean $(MAKE) -C tests clean
include docker.mk
include docs.mk
+9 -23
View File
@@ -1,41 +1,27 @@
ROOT_DIR := $(abspath ..) CXXFLAGS := \
-I$(ROOT_DIR)/app/include \
CC := gcc
CXXFLAGS := -std=c++17 \
-Wall \
-Wextra \
-Werror \
-I$(ROOT_DIR)/core/include \ -I$(ROOT_DIR)/core/include \
-I$(ROOT_DIR)/logger/include -I$(ROOT_DIR)/logger/include
LDFLAGS := -L$(ROOT_DIR)/build \ LDFLAGS := -L$(ROOT_DIR)/build \
-llogger \ -Wl,-rpath,'$$ORIGIN'
-lstdc++ \
-Wl,-rpath,$(ROOT_DIR)/build
BUILD_DIR := $(ROOT_DIR)/build LDLIBS += -llogger
TARGET := $(BUILD_DIR)/logger_app TARGET := $(BUILD_DIR)/logger_app
SRC := src/main.cpp SRC := \
src/main.cpp \
src/message_queue.cpp \
src/logger_worker.cpp
.PHONY: all clean .PHONY: all clean
all: $(TARGET) all: $(TARGET)
$(TARGET): $(SRC) $(TARGET): $(SRC)
@mkdir -p $(BUILD_DIR) @mkdir -p $(BUILD_DIR)
$(CC) $(CXXFLAGS) $(LDFLAGS) $^ -o $@ $(LDLIBS)
$(CC) \
$(CXXFLAGS) \
$< \
-o $@ \
$(LDFLAGS)
clean: clean:
rm -f $(TARGET) rm -f $(TARGET)
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#include <string>
#include "log_level.hpp"
namespace app {
/**
* @brief Сообщение, передаваемое в поток записи.
*
* Содержит текст сообщения и уровень логирования,
* с которым оно должно быть записано в журнал.
*/
struct LogMessage {
/**
* @brief Уровень логирования сообщения.
*/
logger::LogLevel level;
/**
* @brief Текст сообщения.
*/
std::string message;
};
} // namespace app
+125
View File
@@ -0,0 +1,125 @@
#pragma once
#include <thread>
#include "logger.hpp"
#include "message_queue.hpp"
namespace app {
/**
* @brief Фоновый поток записи сообщений в журнал.
*
* LoggerWorker получает сообщения из MessageQueue и передаёт их
* в библиотеку Logger для записи в файл.
*
* Logger передаётся в worker по значению и перемещается внутрь объекта.
* LoggerWorker становится владельцем логгера.
*
* Объект Logger используется только внутри рабочего потока,
* поэтому потокобезопасность Logger не требуется.
*/
class LoggerWorker {
public:
/**
* @brief Создаёт worker для записи сообщений.
*
* Переданный Logger перемещается внутрь объекта LoggerWorker.
*
* @param logger Логгер, используемый для записи.
* @param queue Очередь сообщений.
*/
LoggerWorker(logger::Logger logger, MessageQueue &queue);
/**
* @brief Останавливает поток записи.
*
* Останавливает очередь сообщений и дожидается завершения
* рабочего потока после обработки оставшихся сообщений.
*/
~LoggerWorker();
/**
* @brief Запрещает копирование worker.
*/
LoggerWorker(const LoggerWorker &) = delete;
/**
* @brief Запрещает копирующее присваивание.
*/
LoggerWorker &operator=(const LoggerWorker &) = delete;
/**
* @brief Разрешает перемещение worker.
*
* Передаёт владение потоком записи и состоянием объекта.
*/
LoggerWorker(LoggerWorker &&) noexcept = default;
/**
* @brief Разрешает перемещающее присваивание worker.
*/
LoggerWorker &operator=(LoggerWorker &&) noexcept = default;
/**
* @brief Запускает поток записи сообщений.
*/
void start();
/**
* @brief Возвращает используемый логгер.
*
* Позволяет получить текущую конфигурацию логгера,
* например имя файла журнала или уровень логирования
* по умолчанию.
*
* @return Константная ссылка на логгер.
*/
[[nodiscard]]
const logger::Logger &getLogger() const;
/**
* @brief Устанавливает новый логгер.
*
* Новый Logger заменяет текущий.
* Переданный объект перемещается внутрь worker.
*
* @param logger Новый логгер.
*/
void setLogger(logger::Logger logger);
/**
* @brief Останавливает обработку сообщений.
*
* После остановки очереди новые сообщения не принимаются.
* Рабочий поток завершится после обработки всех сообщений,
* которые уже находились в очереди.
*/
void stop();
private:
/**
* @brief Основной цикл рабочего потока.
*/
void process();
private:
/**
* @brief Логгер для записи сообщений.
*
* Используется только рабочим потоком.
*/
logger::Logger logger_;
/**
* @brief Очередь входящих сообщений.
*/
MessageQueue &queue_;
/**
* @brief Поток записи.
*/
std::thread workerThread_;
};
} // namespace app
+91
View File
@@ -0,0 +1,91 @@
#pragma once
#include <condition_variable>
#include <mutex>
#include <optional>
#include <queue>
#include "log_message.hpp"
namespace app {
/**
* @brief Потокобезопасная очередь сообщений.
*
* Используется для передачи сообщений от потока,
* принимающего ввод пользователя, к потоку,
* выполняющему запись в журнал.
*/
class MessageQueue {
public:
/**
* @brief Добавляет сообщение в очередь.
*
* Метод является потокобезопасным.
*
* После остановки очереди новые сообщения не принимаются.
*
* @param message Сообщение для передачи.
*/
void push(LogMessage message);
/**
* @brief Извлекает сообщение из очереди.
*
* Если очередь пуста, метод блокирует вызывающий поток
* до появления нового сообщения или до остановки очереди.
*
* После остановки очереди и обработки всех оставшихся сообщений
* возвращается std::nullopt.
*
* Метод является потокобезопасным.
*
* @return Следующее сообщение или std::nullopt, если очередь остановлена.
*/
[[nodiscard]]
std::optional<LogMessage> pop();
/**
* @brief Останавливает очередь.
*
* Пробуждает все ожидающие потоки. После вызова stop()
* новые сообщения не принимаются.
*
* Метод является потокобезопасным.
*/
void stop();
/**
* @brief Проверяет, пуста ли очередь.
*
* Метод является потокобезопасным.
*
* @return true, если очередь не содержит сообщений.
* @return false, если очередь содержит хотя бы одно сообщение.
*/
[[nodiscard]]
bool empty() const;
private:
/**
* @brief Очередь сообщений.
*/
std::queue<LogMessage> queue_;
/**
* @brief Признак остановки очереди.
*/
bool stopped_{false};
/**
* @brief Мьютекс для синхронизации доступа к очереди.
*/
mutable std::mutex mutex_;
/**
* @brief Условная переменная для ожидания новых сообщений.
*/
std::condition_variable conditionVariable_;
};
} // namespace app
+41
View File
@@ -0,0 +1,41 @@
#include "logger_worker.hpp"
#include <iostream>
#include <utility>
namespace app {
LoggerWorker::LoggerWorker(logger::Logger logger, MessageQueue &queue)
: logger_(std::move(logger)), queue_(queue) {}
LoggerWorker::~LoggerWorker() { stop(); }
void LoggerWorker::start() {
workerThread_ = std::thread(&LoggerWorker::process, this);
}
void LoggerWorker::stop() {
queue_.stop();
if (workerThread_.joinable()) {
workerThread_.join();
}
}
const logger::Logger &LoggerWorker::getLogger() const { return logger_; }
void LoggerWorker::setLogger(logger::Logger logger) {
logger_ = std::move(logger);
}
void LoggerWorker::process() {
while (auto message = queue_.pop()) {
auto status = logger_.writeMessage(message->level, message->message);
if (!status.isSuccess()) {
std::cerr << "Logger error: " << status.getError() << '\n';
}
}
}
} // namespace app
+203 -4
View File
@@ -1,17 +1,216 @@
#include <iostream> #include <iostream>
#include <string>
#include "logger.hpp" #include "logger.hpp"
#include "logger_worker.hpp"
#include "message_queue.hpp"
namespace {
void printMainMenu() {
std::cout << "\n*** Logger ***\n"
<< " 1: [w]rite message\n"
<< " 2: [c]onfigure\n"
<< " 3: [q]uit\n"
<< "What now> ";
}
void printConfigureMenu() {
std::cout << "\n*** Configure ***\n"
<< " 1: change [d]efault level\n"
<< " 2: change [c]urrent level\n"
<< " 3: [b]ack\n"
<< "What now> ";
}
void printWriteMenu() {
std::cout << "\n*** Write Message ***\n"
<< " 1: use [d]efault level\n"
<< " 2: use [c]urrent level\n"
<< " 3: [b]ack\n"
<< "What now> ";
}
void printLogLevelMenu(const std::string &title,
logger::LogLevel currentLevel) {
std::cout << "\n*** " << title << " ***\n"
<< "\nCurrent: " << currentLevel.toString() << "\n\n"
<< " 1: [d]ebug\n"
<< " 2: [i]nfo\n"
<< " 3: [e]rror\n"
<< " 4: [b]ack\n"
<< "Select level> ";
}
char readCommand() {
std::string command;
std::getline(std::cin, command);
return command.empty() ? '\0' : command.front();
}
} // namespace
int main() { int main() {
logger::Logger logger("app.log", logger::LogLevel::info()); logger::Logger logger("app.log", logger::LogLevel::info());
auto status = logger.writeMessage("Hello from shared library"); app::MessageQueue queue;
app::LoggerWorker worker(std::move(logger), queue);
if (!status.isSuccess()) { worker.start();
std::cerr << status.getError() << '\n';
return 1; logger::LogLevel currentLevel = logger::LogLevel::info();
bool running = true;
while (running) {
printMainMenu();
switch (readCommand()) {
case 'w': {
bool writing = true;
while (writing) {
printWriteMenu();
std::optional<logger::LogLevel> level;
switch (readCommand()) {
case 'd':
level = worker.getLogger().getLogLevel();
break;
case 'c':
level = currentLevel;
break;
case 'b':
writing = false;
continue;
default:
std::cout << "Unknown command.\n";
continue;
} }
std::cout << "Message> ";
std::string message;
std::getline(std::cin, message);
queue.push({*level, message});
writing = false;
}
break;
}
case 'c': {
bool configuring = true;
while (configuring) {
printConfigureMenu();
switch (readCommand()) {
case 'd': {
bool selecting = true;
while (selecting) {
printLogLevelMenu("Default Log Level",
worker.getLogger().getLogLevel());
switch (readCommand()) {
case 'd':
worker.setLogger(
worker.getLogger().withLogLevel(logger::LogLevel::debug()));
selecting = false;
break;
case 'i':
worker.setLogger(
worker.getLogger().withLogLevel(logger::LogLevel::info()));
selecting = false;
break;
case 'e':
worker.setLogger(
worker.getLogger().withLogLevel(logger::LogLevel::error()));
selecting = false;
break;
case 'b':
selecting = false;
break;
default:
std::cout << "Unknown command.\n";
break;
}
}
break;
}
case 'c': {
bool selecting = true;
while (selecting) {
printLogLevelMenu("Current Log Level", currentLevel);
switch (readCommand()) {
case 'd':
currentLevel = logger::LogLevel::debug();
selecting = false;
break;
case 'i':
currentLevel = logger::LogLevel::info();
selecting = false;
break;
case 'e':
currentLevel = logger::LogLevel::error();
selecting = false;
break;
case 'b':
selecting = false;
break;
default:
std::cout << "Unknown command.\n";
break;
}
}
break;
}
case 'b':
configuring = false;
break;
default:
std::cout << "Unknown command.\n";
break;
}
}
break;
}
case 'q':
running = false;
break;
default:
std::cout << "Unknown command.\n";
break;
}
}
worker.stop();
return 0; return 0;
} }
+50
View File
@@ -0,0 +1,50 @@
#include "message_queue.hpp"
namespace app {
void MessageQueue::push(LogMessage message) {
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return;
}
queue_.push(std::move(message));
conditionVariable_.notify_one();
}
std::optional<LogMessage> MessageQueue::pop() {
std::unique_lock<std::mutex> lock(mutex_);
conditionVariable_.wait(lock,
[this]() { return stopped_ || !queue_.empty(); });
if (queue_.empty()) {
return std::nullopt;
}
auto message = std::move(queue_.front());
queue_.pop();
return message;
}
void MessageQueue::stop() {
{
std::lock_guard<std::mutex> lock(mutex_);
stopped_ = true;
}
conditionVariable_.notify_all();
}
bool MessageQueue::empty() const {
std::lock_guard<std::mutex> lock(mutex_);
return queue_.empty();
}
} // namespace app
+36
View File
@@ -0,0 +1,36 @@
DOCKER_IMAGE := threaded-logger-test
.PHONY: docker-build docker-run docker-shell docker-test docker-clean
docker-build:
docker build \
-t $(DOCKER_IMAGE) \
.
docker-run:
docker run \
--rm \
-it \
-v $(ROOT_DIR):/project \
-w /project \
$(DOCKER_IMAGE)
docker-shell:
docker run \
--rm \
-it \
-v $(ROOT_DIR):/project \
-w /project \
$(DOCKER_IMAGE) \
bash
docker-test:
docker run \
--rm \
-v $(ROOT_DIR):/project \
-w /project \
$(DOCKER_IMAGE) \
make clean all
docker-clean:
docker rmi $(DOCKER_IMAGE)
+9
View File
@@ -0,0 +1,9 @@
DOXYGEN_CONFIG := Doxyfile
.PHONY: docs docs-clean
docs:
doxygen $(DOXYGEN_CONFIG)
docs-clean:
rm -rf docs
+8 -24
View File
@@ -1,40 +1,24 @@
ROOT_DIR := $(abspath ..) CXXFLAGS += \
CC := gcc
CXXFLAGS := -std=c++17 \
-Wall \
-Wextra \
-Werror \
-fPIC \
-I$(ROOT_DIR)/core/include \ -I$(ROOT_DIR)/core/include \
-Iinclude -Iinclude
LDFLAGS := -lstdc++ LDFLAGS := \
-shared \
BUILD_DIR := $(ROOT_DIR)/build -Wl,--no-undefined
TARGET := $(BUILD_DIR)/liblogger.so TARGET := $(BUILD_DIR)/liblogger.so
SRC := src/logger.cpp SRC := \
src/logger.cpp \
src/time_utils.cpp
.PHONY: all clean .PHONY: all clean
all: $(TARGET) all: $(TARGET)
$(TARGET): $(SRC) $(TARGET): $(SRC)
@mkdir -p $(BUILD_DIR) @mkdir -p $(BUILD_DIR)
$(CC) $(CXXFLAGS) $(LDFLAGS) $^ -o $@ $(LDLIBS)
$(CC) \
$(CXXFLAGS) \
-shared \
$< \
-o $@ \
$(LDFLAGS)
clean: clean:
rm -f $(TARGET) rm -f $(TARGET)
+13 -1
View File
@@ -63,8 +63,20 @@ public:
return !(*this == other); return !(*this == other);
} }
/**
* @brief Проверяет, является ли текущий уровень менее важным.
*
* Используется для фильтрации сообщений:
* сообщения с уровнем ниже заданного уровня Logger
* не должны записываться в журнал.
*/
[[nodiscard]]
bool operator<(const LogLevel &other) const {
return static_cast<int>(type_) < static_cast<int>(other.type_);
}
private: private:
enum class Type { Debug, Info, Error }; enum class Type { Debug = 0, Info = 1, Error = 2 };
explicit LogLevel(Type type) : type_(type) {} explicit LogLevel(Type type) : type_(type) {}
+24 -5
View File
@@ -49,14 +49,18 @@ public:
Logger &operator=(const Logger &) = delete; Logger &operator=(const Logger &) = delete;
/** /**
* @brief Запрещает перемещение Logger. * @brief Разрешает перемещение Logger.
*
* Передаёт владение ресурсами новому объекту.
*/ */
Logger(Logger &&) = delete; Logger(Logger &&) noexcept = default;
/** /**
* @brief Запрещает перемещающее присваивание. * @brief Разрешает перемещающее присваивание.
*
* Передаёт владение ресурсами новому объекту.
*/ */
Logger &operator=(Logger &&) = delete; Logger &operator=(Logger &&) noexcept = default;
/** /**
* @brief Записывает сообщение в журнал с указанным уровнем логирования. * @brief Записывает сообщение в журнал с указанным уровнем логирования.
@@ -65,6 +69,11 @@ public:
* При ошибке открытия файла или записи возвращается Status * При ошибке открытия файла или записи возвращается Status
* с описанием ошибки. * с описанием ошибки.
* *
* @warning Класс Logger не является потокобезопасным.
* Одновременный вызов данного метода из нескольких потоков
* для одного и того же экземпляра Logger или одного файла журнала
* может привести к неопределённому порядку записей.
*
* @param level Уровень логирования сообщения. * @param level Уровень логирования сообщения.
* @param message Текст сообщения. * @param message Текст сообщения.
* *
@@ -81,6 +90,11 @@ public:
* writeMessage(getLogLevel(), message); * writeMessage(getLogLevel(), message);
* @endcode * @endcode
* *
* @warning Класс Logger не является потокобезопасным.
* Одновременный вызов данного метода из нескольких потоков
* для одного и того же экземпляра Logger или одного файла журнала
* может привести к неопределённому порядку записей.
*
* @param message Текст сообщения. * @param message Текст сообщения.
* *
* @return Статус выполнения операции. * @return Статус выполнения операции.
@@ -130,7 +144,12 @@ private:
std::string fileName_; std::string fileName_;
/** /**
* @brief Уровень логирования по умолчанию. * @brief Создаёт объект логгера.
*
* @param fileName Имя файла, в который будут записываться сообщения.
* @param defaultLevel Уровень логирования по умолчанию и минимальный уровень
* важности сообщений, которые будут записываться в
* журнал.
*/ */
LogLevel defaultLevel_; LogLevel defaultLevel_;
}; };
+10 -1
View File
@@ -2,6 +2,8 @@
#include <fstream> #include <fstream>
#include "time_utils.hpp"
namespace logger { namespace logger {
Logger::Logger(const std::string &fileName, LogLevel defaultLevel) Logger::Logger(const std::string &fileName, LogLevel defaultLevel)
@@ -10,13 +12,20 @@ Logger::Logger(const std::string &fileName, LogLevel defaultLevel)
Logger::~Logger() = default; Logger::~Logger() = default;
core::Status Logger::writeMessage(LogLevel level, const std::string &message) { core::Status Logger::writeMessage(LogLevel level, const std::string &message) {
if (level < defaultLevel_) {
return core::Status::Success(true);
}
// std::ios::app — режим добавления в конец файла
// без удаления уже существующих записей.
std::ofstream stream(fileName_, std::ios::app); std::ofstream stream(fileName_, std::ios::app);
if (!stream.is_open()) { if (!stream.is_open()) {
return core::Status::Failure("Unable to open log file: " + fileName_); return core::Status::Failure("Unable to open log file: " + fileName_);
} }
stream << "[" << level.toString() << "] " << message << '\n'; stream << '[' << time::getCurrentTimestamp() << "] [" << level.toString()
<< "] " << message << '\n';
if (!stream.good()) { if (!stream.good()) {
return core::Status::Failure("Failed to write to log file: " + fileName_); return core::Status::Failure("Failed to write to log file: " + fileName_);
+29
View File
@@ -0,0 +1,29 @@
#include "time_utils.hpp"
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
namespace logger::time {
std::string getCurrentTimestamp() {
const auto now = std::chrono::system_clock::now();
const std::time_t currentTime = std::chrono::system_clock::to_time_t(now);
std::tm localTime{};
#if defined(_WIN32)
localtime_s(&localTime, &currentTime);
#else
localtime_r(&currentTime, &localTime);
#endif
std::ostringstream stream;
stream << std::put_time(&localTime, "%Y-%m-%d %H:%M:%S");
return stream.str();
}
} // namespace logger::time
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include <string>
namespace logger::time {
/**
* @brief Возвращает текущее локальное время.
*
* Время возвращается в формате:
*
* @code
* YYYY-MM-DD HH:MM:SS
* @endcode
*
* @return Текущее локальное время в виде строки.
*/
std::string getCurrentTimestamp();
} // namespace logger::time
+8 -56
View File
@@ -1,61 +1,13 @@
ROOT_DIR := $(abspath ..) ROOT_DIR := $(abspath ..)
CXX := gcc .PHONY: all clean
CXXFLAGS := -std=c++17 \
-Wall \
-Wextra \
-Werror \
-I$(ROOT_DIR)/core/include \
-I$(ROOT_DIR)/logger/include \
-Ihelpers
LDFLAGS := -lstdc++
BUILD_DIR := $(ROOT_DIR)/build
RESULT_TEST_BIN := $(BUILD_DIR)/result_test
LOGGER_TEST_BIN := $(BUILD_DIR)/logger_test
SCOPED_FILE_TEST_BIN := $(BUILD_DIR)/scoped_file_test
RESULT_TEST_SRC := core/result_test.cpp
LOGGER_TEST_SRC := core/logger_test.cpp
SCOPED_FILE_TEST_SRC := helpers/scoped_file_test.cpp
LOGGER_SRC := $(ROOT_DIR)/logger/src/logger.cpp
.PHONY: all test clean
all: test
test: $(RESULT_TEST_BIN) \
$(LOGGER_TEST_BIN) \
$(SCOPED_FILE_TEST_BIN)
$(RESULT_TEST_BIN)
$(LOGGER_TEST_BIN)
$(SCOPED_FILE_TEST_BIN)
$(RESULT_TEST_BIN): $(RESULT_TEST_SRC)
@mkdir -p $(BUILD_DIR)
$(CXX) $(CXXFLAGS) $< -o $@ $(LDFLAGS)
$(LOGGER_TEST_BIN): $(LOGGER_TEST_SRC) $(LOGGER_SRC)
@mkdir -p $(BUILD_DIR)
$(CXX) $(CXXFLAGS) $^ -o $@ $(LDFLAGS)
$(SCOPED_FILE_TEST_BIN): $(SCOPED_FILE_TEST_SRC)
@mkdir -p $(BUILD_DIR)
$(CXX) $(CXXFLAGS) $< -o $@ $(LDFLAGS)
all:
$(MAKE) -C app
$(MAKE) -C core
$(MAKE) -C logger
clean: clean:
rm -rf $(BUILD_DIR) $(MAKE) -C app clean
$(MAKE) -C core clean
$(MAKE) -C logger clean
+23
View File
@@ -0,0 +1,23 @@
CXXFLAGS += \
-I$(ROOT_DIR)/app/include \
-I$(ROOT_DIR)/logger/include \
-Ihelpers
TARGET := $(BUILD_DIR)/app_test
SRC := \
$(ROOT_DIR)/app/src/message_queue.cpp \
helpers/thread_test_utils.cpp \
message_queue_test.cpp
.PHONY: all clean
all: $(TARGET)
$(TARGET)
$(TARGET): $(SRC)
@mkdir -p $(BUILD_DIR)
$(CC) $(CXXFLAGS) $^ -o $@ $(LDLIBS)
clean:
rm -f $(TARGET)
+23
View File
@@ -0,0 +1,23 @@
#include "thread_test_utils.hpp"
#include <cassert>
#include <cstddef>
#include <thread>
namespace app::tests::helpers {
std::thread createProducer(MessageQueue &queue, std::size_t threadIndex,
std::size_t messagesCount) {
return std::thread([&queue, threadIndex, messagesCount]() {
for (std::size_t messageIndex = 0; messageIndex < messagesCount;
++messageIndex) {
queue.push({
logger::LogLevel::info(),
"Thread " + std::to_string(threadIndex) + ", message " +
std::to_string(messageIndex),
});
}
});
}
} // namespace app::tests::helpers
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <cstddef>
#include <thread>
#include "message_queue.hpp"
namespace app::tests::helpers {
std::thread createProducer(MessageQueue &queue, std::size_t threadIndex,
std::size_t messagesCount);
} // namespace app::tests::helpers
+142
View File
@@ -0,0 +1,142 @@
#include <cassert>
#include <thread>
#include <vector>
#include "log_level.hpp"
#include "message_queue.hpp"
#include "thread_test_utils.hpp"
namespace app::tests {
using namespace app;
void testPushAndPop() {
MessageQueue queue;
queue.push({logger::LogLevel::info(), "Hello"});
auto message = queue.pop();
assert(message.has_value());
assert(message->level == logger::LogLevel::info());
assert(message->message == "Hello");
}
void testFifoOrder() {
MessageQueue queue;
queue.push({logger::LogLevel::debug(), "first"});
queue.push({logger::LogLevel::info(), "second"});
queue.push({logger::LogLevel::error(), "third"});
assert(queue.pop()->message == "first");
assert(queue.pop()->message == "second");
assert(queue.pop()->message == "third");
}
void testPopWaitsForMessage() {
MessageQueue queue;
bool received = false;
std::thread worker([&]() {
auto message = queue.pop();
assert(message.has_value());
assert(message->level == logger::LogLevel::error());
assert(message->message == "Delayed");
received = true;
});
// Даём потоку worker возможность дойти до queue.pop()
// и заблокироваться в ожидании сообщения.
std::this_thread::sleep_for(std::chrono::milliseconds(100));
assert(!received);
// Добавляем сообщение и тем самым разблокируем worker.
queue.push({logger::LogLevel::error(), "Delayed"});
// Ожидаем полного завершения потока worker.
worker.join();
assert(received);
}
void testConcurrentPushAndPop() {
MessageQueue queue;
constexpr std::size_t threadCount = 8;
constexpr std::size_t messagesPerThread = 1000;
std::vector<std::thread> producers;
for (std::size_t i = 0; i < threadCount; ++i) {
producers.emplace_back(
helpers::createProducer(queue, i, messagesPerThread));
}
const auto expectedMessages = threadCount * messagesPerThread;
for (std::size_t i = 0; i < expectedMessages; ++i) {
auto message = queue.pop();
assert(message.has_value());
assert(!message->message.empty());
}
for (auto &producer : producers) {
producer.join();
}
assert(queue.empty());
}
void testStopReturnsNullopt() {
MessageQueue queue;
queue.stop();
auto message = queue.pop();
assert(!message.has_value());
}
void testStopReturnsRemainingMessages() {
MessageQueue queue;
queue.push({logger::LogLevel::info(), "first"});
queue.push({logger::LogLevel::error(), "second"});
queue.stop();
auto first = queue.pop();
auto second = queue.pop();
auto third = queue.pop();
assert(first.has_value());
assert(first->message == "first");
assert(second.has_value());
assert(second->message == "second");
assert(!third.has_value());
}
void runTests() {
testPushAndPop();
testFifoOrder();
testPopWaitsForMessage();
testConcurrentPushAndPop();
testStopReturnsNullopt();
testStopReturnsRemainingMessages();
}
} // namespace app::tests
int main() {
app::tests::runTests();
return 0;
}
+18
View File
@@ -0,0 +1,18 @@
CXXFLAGS += \
-I$(ROOT_DIR)/core/include
TARGET := $(BUILD_DIR)/result_test
SRC := result_test.cpp
.PHONY: all clean
all: $(TARGET)
$(TARGET)
$(TARGET): $(SRC)
@mkdir -p $(BUILD_DIR)
$(CC) $(CXXFLAGS) $^ -o $@ $(LDLIBS)
clean:
rm -f $(TARGET)
-123
View File
@@ -1,123 +0,0 @@
#include <cassert>
#include <fstream>
#include <string>
#include "logger.hpp"
namespace {
using namespace logger;
void testLoggerCreation() {
Logger logger("test.log", LogLevel::info());
assert(logger.getFileName() == "test.log");
assert(logger.getLogLevel() == LogLevel::info());
}
void testWithLogLevel() {
Logger logger("test.log", LogLevel::info());
auto debugLogger = logger.withLogLevel(LogLevel::debug());
// Исходный объект не изменился
assert(logger.getLogLevel() == LogLevel::info());
// Новый объект получил новый уровень
assert(debugLogger.getLogLevel() == LogLevel::debug());
// Имя файла сохранилось
assert(debugLogger.getFileName() == "test.log");
}
void testWithFileName() {
Logger logger("old.log", LogLevel::info());
auto newLogger = logger.withFileName("new.log");
// Исходный объект не изменился
assert(logger.getFileName() == "old.log");
// Новый объект получил новый файл
assert(newLogger.getFileName() == "new.log");
// Уровень сохранился
assert(newLogger.getLogLevel() == LogLevel::info());
}
void testWriteLogSuccess() {
const std::string fileName = "logger_test.log";
Logger logger(fileName, LogLevel::info());
auto result = logger.writeMessage(LogLevel::info(), "Application started");
assert(result.isSuccess());
assert(result.getValue());
std::ifstream file(fileName);
assert(file.is_open());
std::string content;
std::getline(file, content);
assert(content.find("Application started") != std::string::npos);
file.close();
std::remove(fileName.c_str());
}
void testWriteLogFailure() {
Logger logger("/invalid/path/logger.log", LogLevel::info());
auto result = logger.writeMessage(LogLevel::info(), "message");
assert(result.isFailure());
assert(!result.getError().empty());
}
void testMultipleWrites() {
const std::string fileName = "multiple.log";
Logger logger(fileName, LogLevel::info());
assert(logger.writeMessage(LogLevel::info(), "first").isSuccess());
assert(logger.writeMessage(LogLevel::error(), "second").isSuccess());
std::ifstream file(fileName);
assert(file.is_open());
std::string line1;
std::string line2;
std::getline(file, line1);
std::getline(file, line2);
assert(line1.find("first") != std::string::npos);
assert(line2.find("second") != std::string::npos);
file.close();
std::remove(fileName.c_str());
}
void runTests() {
testLoggerCreation();
testWithLogLevel();
testWithFileName();
testWriteLogSuccess();
testWriteLogFailure();
testMultipleWrites();
}
} // namespace
int main() {
runTests();
return 0;
}
+3 -3
View File
@@ -4,7 +4,7 @@
#include "result.hpp" #include "result.hpp"
namespace { namespace core::tests {
using namespace core; using namespace core;
@@ -108,9 +108,9 @@ void runAllTests() {
testBasicResultWithCustomError(); testBasicResultWithCustomError();
} }
} // namespace } // namespace core::tests
int main() { int main() {
runAllTests(); core::tests::runAllTests();
return 0; return 0;
} }
+27
View File
@@ -0,0 +1,27 @@
CXXFLAGS += \
-I$(ROOT_DIR)/core/include \
-I$(ROOT_DIR)/logger/include \
-Ihelpers
TARGET := $(BUILD_DIR)/logger_test
SRC := \
$(ROOT_DIR)/logger/src/logger.cpp \
$(ROOT_DIR)/logger/src/time_utils.cpp \
logger_test.cpp
.PHONY: all clean helpers
all: helpers $(TARGET)
$(TARGET)
helpers:
$(MAKE) -C helpers
$(TARGET): $(SRC)
@mkdir -p $(BUILD_DIR)
$(CC) $(CXXFLAGS) $^ -o $@ $(LDLIBS)
clean:
rm -f $(TARGET)
$(MAKE) -C helpers clean
+15
View File
@@ -0,0 +1,15 @@
TARGET := $(BUILD_DIR)/scoped_file_test
SRC := scoped_file_test.cpp
.PHONY: all clean
all: $(TARGET)
$(TARGET)
$(TARGET): $(SRC)
@mkdir -p $(BUILD_DIR)
$(CC) $(CXXFLAGS) $^ -o $@ $(LDLIBS)
clean:
rm -f $(TARGET)
@@ -4,7 +4,7 @@
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
namespace helpers { namespace logger::tests::helpers {
class ScopedFile { class ScopedFile {
public: public:
@@ -28,4 +28,4 @@ private:
std::string fileName_; std::string fileName_;
}; };
} // namespace helpers } // namespace logger::tests::helpers
@@ -8,7 +8,7 @@
namespace { namespace {
using namespace helpers; using namespace logger::tests::helpers;
void testFileRemovedAfterScope() { void testFileRemovedAfterScope() {
const std::string fileName = "scoped_file_test.log"; const std::string fileName = "scoped_file_test.log";
+68 -6
View File
@@ -6,7 +6,7 @@
#include "logger.hpp" #include "logger.hpp"
#include "scoped_file.hpp" #include "scoped_file.hpp"
namespace { namespace logger::tests {
using namespace logger; using namespace logger;
@@ -40,7 +40,7 @@ void testWithFileName() {
} }
void testWriteLogSuccess() { void testWriteLogSuccess() {
ScopedFile file("logger_test.log"); helpers::ScopedFile file("logger_test.log");
file.throwIfExists(); file.throwIfExists();
@@ -62,7 +62,7 @@ void testWriteLogSuccess() {
} }
void testWriteLogFailure() { void testWriteLogFailure() {
ScopedFile file("logger_test_directory"); helpers::ScopedFile file("logger_test_directory");
file.throwIfExists(); file.throwIfExists();
@@ -79,12 +79,14 @@ void testWriteLogFailure() {
} }
void testMultipleWrites() { void testMultipleWrites() {
ScopedFile file("multiple.log"); helpers::ScopedFile file("multiple.log");
file.throwIfExists(); file.throwIfExists();
Logger logger(file.getFileName(), LogLevel::info()); Logger logger(file.getFileName(), LogLevel::info());
// NOTE: Ресурс файла был автоматически освобождён после первого вызова,
// поэтому следующий вызов может повторно открыть файл для записи
auto first = logger.writeMessage(LogLevel::info(), "first message"); auto first = logger.writeMessage(LogLevel::info(), "first message");
auto second = logger.writeMessage(LogLevel::error(), "second message"); auto second = logger.writeMessage(LogLevel::error(), "second message");
@@ -107,6 +109,64 @@ void testMultipleWrites() {
assert(secondLine.find("second message") != std::string::npos); assert(secondLine.find("second message") != std::string::npos);
} }
void testIgnoreLowerLogLevel() {
helpers::ScopedFile file("filter.log");
file.throwIfExists();
Logger logger(file.getFileName(), LogLevel::info());
// INFO соответствует минимальному уровню логирования,
// поэтому сообщение должно быть записано в журнал
auto infoResult = logger.writeMessage(LogLevel::info(), "info message");
assert(infoResult.isSuccess());
// DEBUG имеет более низкий приоритет, чем установленный уровень INFO.
// Сообщение не должно попасть в журнал
auto debugResult = logger.writeMessage(LogLevel::debug(), "debug message");
assert(debugResult.isSuccess());
std::ifstream input(file.getFileName());
assert(input.is_open());
std::string firstLine;
std::string secondLine;
std::getline(input, firstLine);
assert(firstLine.find("info message") != std::string::npos);
// Проверяем, что после INFO-сообщения отсутствует DEBUG-сообщение.
bool hasSecondLine = static_cast<bool>(std::getline(input, secondLine));
assert(!hasSecondLine);
}
void testWriteMessageWithDefaultLevel() {
helpers::ScopedFile file("default_level.log");
file.throwIfExists();
Logger logger(file.getFileName(), LogLevel::error());
auto result = logger.writeMessage("critical message");
assert(result.isSuccess());
std::ifstream input(file.getFileName());
assert(input.is_open());
std::string content;
std::getline(input, content);
assert(content.find("critical message") != std::string::npos);
}
void runTests() { void runTests() {
testLoggerCreation(); testLoggerCreation();
testWithLogLevel(); testWithLogLevel();
@@ -114,12 +174,14 @@ void runTests() {
testWriteLogSuccess(); testWriteLogSuccess();
testWriteLogFailure(); testWriteLogFailure();
testMultipleWrites(); testMultipleWrites();
testIgnoreLowerLogLevel();
testWriteMessageWithDefaultLevel();
} }
} // namespace } // namespace logger::tests
int main() { int main() {
runTests(); logger::tests::runTests();
return 0; return 0;
} }