Getting Started
Prerequisites
Required
- CMake 3.25+
- C++20 Compiler: Clang 15+, GCC 11+, or MSVC 2019+
GUI Framework
Qt 6 (required — includes AI features):
- Qt 6: 6.5 or higher
- Windows: Download Qt installer from qt.io or use vcpkg
- macOS:
brew install qt@6
- Linux:
sudo apt-get install qt6-base-dev (Ubuntu/Debian)
- CURL: For AI provider HTTP requests
- Windows: Available through vcpkg
- macOS: Included by default
- Linux:
sudo apt-get install libcurl4-openssl-dev
Optional but Recommended
- Ninja build system (recommended for faster builds)
- Windows: Available through package managers (choco, scoop)
- macOS:
brew install ninja
- Linux:
sudo apt-get install ninja-build
- ccache (optional, for faster rebuilds)
- clang-format: For code formatting
- clang-tidy: For static analysis
- Doxygen: For documentation generation
Quick Start
# Clone repository
git clone https://github.com/bula173/LogViewer.git
cd LogViewer
# Configure and build (Debug) - macOS example
cmake --preset macos-debug-qt
cmake --build --preset macos-debug-build-qt
# Run tests
ctest --preset macos-debug-test-qt
# Run application from build directory
./build/macos-debug-qt/bin/LogViewer.app/Contents/MacOS/LogViewer
# or use the script
./scripts/run_debug.sh
Platform-specific presets:
- macOS:
macos-debug-qt, macos-release-qt
- Windows (MSYS2):
windows-msys-debug-qt, windows-msys-release-qt
- Linux:
linux-debug-qt, linux-release-qt
Using VS Code Tasks (Recommended):
The project includes pre-configured tasks accessible via Cmd+Shift+P (macOS) or Ctrl+Shift+P (Windows/Linux) > "Tasks: Run Task":
- Build Debug - Configure and build debug version
- Build Release - Configure and build release version
- Run App (Debug) - Build and run debug application
- Test Debug - Build and run tests
- Static Analysis (cppcheck) - Run static analysis
- Package Release - Create distributable package
Build System Architecture
Directory Structure
The build system separates build artifacts from distribution files:
LogViewer/
├── build/ # Build outputs (not in git)
│ └── <preset-name>/ # e.g., macos-debug-qt
│ ├── bin/ # Executables for development
│ │ ├── LogViewer.app/
│ │ └── etc/ # Config files copied here
│ ├── lib/ # Static libraries
│ ├── plugins/ # Plugin shared libraries (.dylib/.so/.dll)
│ │ ├── ai_provider.dylib
│ │ ├── ai_provider.zip # Plugin packages
│ │ └── *_package/ # Temporary packaging directories
│ └── CMakeFiles/ # CMake internal files
├── dist/ # Distribution files
│ ├── packages/ # Final installers (.dmg, .zip, .exe)
│ │ └── LogViewer-1.0.0-Darwin.dmg
│ └── staging/ # Install staging (not in git)
│ ├── LogViewer.app/
│ ├── etc/
│ └── plugins/
└── src/ # Source code
CMake Output Directories
The build system uses standard CMake output directories:
CMAKE_RUNTIME_OUTPUT_DIRECTORY: build/<preset>/bin - Executables
CMAKE_LIBRARY_OUTPUT_DIRECTORY: build/<preset>/lib - Shared libraries
CMAKE_ARCHIVE_OUTPUT_DIRECTORY: build/<preset>/lib - Static libraries
Development workflow:
- Build:
cmake --build --preset <preset>
- Run from build:
./build/<preset>/bin/LogViewer.app/...
- All outputs stay in
build/ directory
Distribution workflow:
- Install:
cmake --install build/<preset> --prefix dist/staging
- Package:
cpack --config build/<preset>/CPackConfig.cmake
- Installers go to
dist/packages/
Scripts
Convenience scripts in scripts/ directory:
build_debug.sh - Build debug version
configure_and_build_osx.sh - Configure and build from scratch
run_debug.sh - Run debug application
- Windows equivalents:
.bat files
All scripts updated to use new directory structure.
Code Style Guide
Naming Conventions
class EventsContainer { };
void parseData();
int getCurrentIndex();
private:
std::string m_fileName;
int m_eventCount;
const int MAX_EVENTS = 1000000;
template<typename T, typename ErrorType>
class Result { };
Data parsing components and interfaces.
Definition IControler.hpp:22
File Organization
#pragma once
#include <vector>
#include <memory>
#include <nlohmann/json.hpp>
#include <QMainWindow>
#include <QTableView>
class EventsContainer {
public:
const LogEvent&
GetEvent(
int index) const;
private:
void validateIndex(int index) const;
};
}
Defines the LogEvent class for representing structured log entries.
void AddEvent(LogEvent &&event)
Adds a new event to the container.
Definition EventsContainer.cpp:28
size_t Size() const override
Gets the number of events in the container.
Definition EventsContainer.cpp:151
const LogEvent & GetEvent(size_t index)
Retrieves an event by index.
Definition EventsContainer.cpp:64
virtual ~EventsContainer()
Destructor.
Definition EventsContainer.cpp:23
std::shared_mutex m_mutex
Definition EventsContainer.hpp:330
std::deque< LogEvent > m_data
Definition EventsContainer.hpp:323
EventsContainer()
Default constructor.
Definition EventsContainer.cpp:18
Database and data model components for the LogViewer application.
Definition EventsContainer.cpp:17
Documentation Standards
Doxygen Comments
void AddEvent(LogEvent&& event);
Code Quality Checklist
Before Committing
- [ ] All tests pass
- [ ] No compiler warnings
- [ ] Code formatted with clang-format
- [ ] Doxygen comments for public APIs
- [ ] Thread safety documented
- [ ] Performance implications noted
- [ ] Error handling implemented
- [ ] Resource cleanup (RAII)
Design Patterns Usage
When to Use Each Pattern
Observer Pattern ✅
Use when: Components need loose coupling for event notification
class XmlParser : public IDataParser {
void ParseData(const std::filesystem::path& filepath) override {
NotifyNewEvent(std::move(event));
}
};
Factory Pattern ✅
Use when: Object creation logic is complex or varies
auto parser = ParserFactory::CreateParser(
".xml");
auto parser = ParserFactory::CreateParser(
".json");
Strategy Pattern ✅
Use when: Algorithm needs to be swappable at runtime
filter.SetStrategy(std::make_unique<RegexStrategy>());
filter.SetStrategy(std::make_unique<ExactMatchStrategy>());
Singleton Pattern ⚠️
Use sparingly: Only for truly global resources
Config&
config = Config::Instance();
Definition BuiltinConversionPlugins.cpp:5
Qt-Specific Patterns
Signals and Slots
Use when: Components need Qt's signal/slot mechanism for event notification
Q_OBJECT
public:
void UpdateData(const EventsContainer& container) {
beginResetModel();
m_data = &container;
endResetModel();
emit dataChanged(index(0, 0), index(rowCount()-1, columnCount()-1));
}
signals:
void filterChanged(const QString& filterText);
void eventSelected(int eventId);
public slots:
void onConfigChanged(
const Config&
config) {
}
};
Model/View Architecture
Use when: Displaying data in Qt views (tables, lists, trees)
Q_OBJECT
public:
int rowCount(const QModelIndex& parent = QModelIndex()) const override {
return m_container ? m_container->Size() : 0;
}
int columnCount(const QModelIndex& parent = QModelIndex()) const override {
return m_config.columns.size();
}
QVariant data(const QModelIndex& index, int role) const override {
if (role == Qt::DisplayRole) {
const auto& event = m_container->GetEvent(index.row());
return QString::fromStdString(event.GetValue(m_config.columns[index.column()]));
}
return QVariant();
}
private:
const EventsContainer* m_container = nullptr;
const Config& m_config;
};
Dock Widget System
Use when: Creating flexible, dockable UI panels
Q_OBJECT
public:
MainWindow() {
m_filtersDock = new QDockWidget(tr("Filters"), this);
m_filtersDock->setWidget(new FiltersPanel(this));
addDockWidget(Qt::LeftDockWidgetArea, m_filtersDock);
m_detailsDock = new QDockWidget(tr("Details"), this);
m_detailsDock->setWidget(new ItemDetailsPanel(this));
addDockWidget(Qt::RightDockWidgetArea, m_detailsDock);
}
private:
QDockWidget* m_filtersDock = nullptr;
QDockWidget* m_detailsDock = nullptr;
};
Error Handling
Error Categories
class Error : public std::exception {
public:
explicit Error(std::string message) : m_message(std::move(message)) {}
const char* what() const noexcept override { return m_message.c_str(); }
private:
std::string m_message;
};
class ConfigError :
public Error {
using Error::Error;
};
};
class FileError :
public Error {
using Error::Error;
};
}
Error(ErrorCode code, const char *message, bool showMsgBox=true)
Definition Error.hpp:67
@ ParseError
Parsing error.
Error Handling Guidelines
try {
DoSomething();
} catch (...) {
}
try {
} catch (const error::ConfigError& e) {
} catch (const error::FileError& e) {
ShowFilePickerDialog();
}
Result<Config, ConfigError> LoadConfig(const std::string& path) {
if (!std::filesystem::exists(path)) {
return Result::Err(ConfigError("File not found"));
}
return Result::Ok(std::move(
config));
}
auto result = LoadConfig(
"config.json");
} else {
}
static void Error(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logger.hpp:303
std::string result
Definition OllamaClient.cpp:144
Thread Safety
Guidelines
- Document thread safety of every class
- Prefer immutability when possible
- Use RAII for lock management
- Avoid deadlocks with lock ordering
class EventsContainer {
public:
void AddEvent(LogEvent&& event) {
std::lock_guard<std::mutex> lock(m_mutex);
m_data.push_back(std::move(event));
}
const LogEvent& GetEvent(int index) const {
std::shared_lock<std::shared_mutex> lock(m_mutex);
return m_data.at(index);
}
size_t Size() const noexcept {
return m_data.size();
}
private:
mutable std::shared_mutex m_mutex;
std::vector<LogEvent> m_data;
};
Performance Best Practices
Memory Management
void ProcessEvents(EventsContainer container) {
}
void ProcessEvents(const EventsContainer& container) {
}
void TakeOwnership(EventsContainer&& container) {
m_container = std::move(container);
}
String Handling
std::string result;
for (const auto& item : items) {
result += item + ", ";
}
std::string result;
result.reserve(estimatedSize);
for (const auto& item : items) {
result += item + ", ";
}
std::ostringstream oss;
for (const auto& item : items) {
oss << item << ", ";
}
std::string
result = oss.str();
Container Operations
std::vector<LogEvent> events;
for (int i = 0; i < 1000000; ++i) {
events.push_back(CreateEvent(i));
}
std::vector<LogEvent> events;
events.reserve(1000000);
for (int i = 0; i < 1000000; ++i) {
events.push_back(CreateEvent(i));
}
events.reserve(1000000);
for (int i = 0; i < 1000000; ++i) {
events.emplace_back(i, CreateItems(i));
}
AI Integration Development
Adding a New AI Provider
The application uses a factory pattern for AI providers. To add a new provider:
1. Implement IAIService Interface
#pragma once
#include <string>
class MyNewAIClient : public IAIService {
public:
MyNewAIClient() = default;
~MyNewAIClient() override = default;
std::string Chat(
const std::string& systemPrompt,
const std::string& userPrompt,
const std::string& model) override;
std::vector<std::string> ListModels() override;
};
}
Definition GemmaInferenceEngine.cpp:18
2. Implement Chat Method with CURL
#include "MyNewAIClient.hpp"
#include <curl/curl.h>
#include <nlohmann/json.hpp>
std::string MyNewAIClient::Chat(
const std::string& systemPrompt,
const std::string& userPrompt,
const std::string& model) {
CURL* curl = curl_easy_init();
if (!curl) {
throw std::runtime_error("Failed to initialize CURL");
}
curl_easy_setopt(curl, CURLOPT_TIMEOUT,
static_cast<long>(
config.aiTimeoutSeconds));
nlohmann::json request = {
{"model", model},
{"messages", nlohmann::json::array({
{{"role", "system"}, {"content", systemPrompt}},
{{"role", "user"}, {"content", userPrompt}}
})}
};
std::string requestBody = request.dump();
std::string response;
curl_easy_setopt(curl, CURLOPT_URL, "https://api.myprovider.com/v1/chat");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, requestBody.c_str());
struct curl_slist* headers = nullptr;
headers = curl_slist_append(headers, "Content-Type: application/json");
std::string authHeader =
"Authorization: Bearer " +
config.aiApiKey;
headers = curl_slist_append(headers, authHeader.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, [](void* contents, size_t size,
size_t nmemb, std::string* s) -> size_t {
s->append((char*)contents, size * nmemb);
return size * nmemb;
});
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
CURLcode res = curl_easy_perform(curl);
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
if (res != CURLE_OK) {
throw std::runtime_error("CURL error: " +
std::string(curl_easy_strerror(res)));
}
auto jsonResponse = nlohmann::json::parse(response);
return jsonResponse["choices"][0]["message"]["content"].get<std::string>();
}
std::vector<std::string> MyNewAIClient::ListModels() {
return {"my-model-1", "my-model-2"};
}
}
Config & GetConfig()
Definition Config.cpp:142
3. Register in AIServiceFactory
#include "MyNewAIClient.hpp"
std::unique_ptr<IAIService> AIServiceFactory::CreateService(
const std::string& provider) {
if (provider == "ollama" || provider == "lmstudio") {
return std::make_unique<OllamaClient>();
} else if (provider == "openai") {
return std::make_unique<OpenAIClient>();
} else if (provider == "mynewai") {
return std::make_unique<MyNewAIClient>();
}
throw std::runtime_error("Unknown AI provider: " + provider);
}
4. Add to Configuration
// etc/default_config.json
{
"aiConfig": {
"provider": "mynewai",
"apiKey": "your-api-key-here",
"defaultModel": "my-model-1",
"timeoutSeconds": 300
}
}
AI Provider Guidelines
Timeout Configuration
- Always use
config.aiTimeoutSeconds from Config
- Valid range: 30-3600 seconds (enforced by UI)
- Default: 300 seconds (5 minutes)
- Why: Slow machines or large analyses need more time
curl_easy_setopt(curl, CURLOPT_TIMEOUT,
static_cast<long>(
config.aiTimeoutSeconds));
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 300L);
Error Handling
- Throw descriptive exceptions for CURL errors
- Throw exceptions for HTTP error status codes
- Throw exceptions for malformed JSON responses
- All exceptions caught and displayed in UI
Thread Safety
- AI requests run in background threads via
QtConcurrent::run()
- Don't access UI directly from AI threads
- Use signals/slots to update UI from background threads
void AIAnalysisPanel::OnAnalyze() {
QString prompt = m_promptEdit->toPlainText();
auto future = QtConcurrent::run([this, prompt]() {
auto aiService = ai::AIServiceFactory::CreateService(
return aiService->Chat(systemPrompt, prompt.toStdString(), model);
});
auto watcher = new QFutureWatcher<std::string>(this);
connect(watcher, &QFutureWatcher<std::string>::finished, this, [this, watcher]() {
try {
QString result = QString::fromStdString(watcher->result());
m_responseEdit->setPlainText(result);
} catch (const std::exception& e) {
QMessageBox::critical(this, tr("Error"), e.what());
}
watcher->deleteLater();
});
watcher->setFuture(future);
}
Filter-Aware Analysis
AI analysis respects typeFilterField, which is auto-detected on file load (or pinned by the user in Settings > General):
std::string filterField =
config.typeFilterField;
for (const auto& event : events) {
std::string filterValue = event.GetValue(filterField);
}
This allows analysis of logs that use different fields for categorization:
"type" - Traditional event types
"level" - Log levels (ERROR, WARN, INFO, DEBUG)
"severity" - Severity levels (CRITICAL, HIGH, MEDIUM, LOW)
"priority" - Priority levels (P0, P1, P2, P3)
Testing
Unit Test Structure
Unit tests are framework-agnostic and test the core business logic, not UI code.
#include <gtest/gtest.h>
namespace db::test {
class EventsContainerTest : public ::testing::Test {
protected:
void SetUp() override {
container = std::make_unique<EventsContainer>();
}
void TearDown() override {
container.reset();
}
std::unique_ptr<EventsContainer> container;
};
TEST_F(EventsContainerTest, AddSingleEvent) {
LogEvent event(1, {{"key", "value"}});
container->AddEvent(std::move(event));
EXPECT_EQ(container->Size(), 1);
EXPECT_EQ(container->GetEvent(0).getId(), 1);
}
TEST_F(EventsContainerTest, ThrowsOnInvalidIndex) {
EXPECT_THROW(container->GetEvent(0), std::out_of_range);
}
TEST_F(EventsContainerTest, MultiThreadedAddition) {
constexpr int NUM_THREADS = 10;
constexpr int EVENTS_PER_THREAD = 1000;
std::vector<std::thread> threads;
for (int t = 0; t < NUM_THREADS; ++t) {
threads.emplace_back([this, t]() {
for (int i = 0; i < EVENTS_PER_THREAD; ++i) {
LogEvent event(t * EVENTS_PER_THREAD + i, {});
container->AddEvent(std::move(event));
}
});
}
for (auto& thread : threads) {
thread.join();
}
EXPECT_EQ(container->Size(), NUM_THREADS * EVENTS_PER_THREAD);
}
}
Container class for managing collections of LogEvent objects.
Mock Objects
class MockObserver : public IDataParserObserver {
public:
MOCK_METHOD(void, ProgressUpdated, (), (override));
MOCK_METHOD(void, NewEventFound, (LogEvent&&), (override));
MOCK_METHOD(void, NewEventBatchFound,
(std::vector<std::pair<int, LogEvent::EventItems>>&&), (override));
};
TEST(XmlParserTest, NotifiesObservers) {
MockObserver observer;
parser.RegisterObserver(&observer);
EXPECT_CALL(observer, NewEventFound(testing::_))
.Times(testing::AtLeast(1));
}
Debugging Tips
Logging Levels
static void Warn(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logger.hpp:297
static void Critical(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logger.hpp:309
static void Trace(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logger.hpp:279
static void Debug(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logger.hpp:285
static void Info(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logger.hpp:291
Common Issues
Issue: Crash on vector access
assert(index < m_data.size() && "Index out of range");
return m_data.at(index);
Issue: Memory leaks
std::unique_ptr<Parser>
parser = ParserFactory::CreateParser(
".xml");
std::shared_ptr<Config>
config = std::make_shared<Config>();
Issue: Deadlocks
class A {
void DoWork() {
std::lock_guard<std::mutex> lock1(m_mutex);
std::lock_guard<std::mutex> lock2(other.m_mutex);
}
};
void DoWork() {
std::scoped_lock lock(m_mutex, other.m_mutex);
}
Git Workflow
Branch Naming
feature/add-json-parser - New features
bugfix/fix-crash-on-empty-file - Bug fixes
refactor/improve-filter-performance - Code improvements
docs/update-architecture - Documentation
Commit Messages
feat: Add JSON parser support
- Implement JsonParser class following IDataParser interface
- Add tests for JSON parsing edge cases
- Update ParserFactory to handle .json files
Closes #123
Pull Request Template
## Description
Brief description of changes
## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
## Testing
- [ ] Unit tests added
- [ ] Integration tests pass
- [ ] Manual testing performed
## Checklist
- [ ] Code follows style guide
- [ ] Documentation updated
- [ ] No new warnings
- [ ] Tests pass locally
Useful Commands
# Format all code
find src -name "*.cpp" -o -name "*.hpp" | xargs clang-format -i
# Run static analysis
clang-tidy src/**/*.cpp -- -I src
# Generate documentation
doxygen Doxyfile
# Run with sanitizers (dedicated presets per sanitizer, see CMakePresets.json)
cmake --preset macos-asan-qt # AddressSanitizer
cmake --build --preset macos-asan-build-qt
./build/macos-asan-qt/bin/LogViewer.app/Contents/MacOS/LogViewer
# Profile performance
perf record ./build/linux-release-qt/bin/LogViewer
perf report
# Memory profiling
valgrind --tool=massif ./build/linux-debug-qt/bin/LogViewer
Resources
C++ and General
Qt Framework
AI Provider APIs