Skip to content

Commit

Permalink
Merge pull request #7 from Kilemonn/move-logging-to-file
Browse files Browse the repository at this point in the history
Introduce Log4cxx logging dependency.
  • Loading branch information
Kilemonn authored Oct 16, 2024
2 parents 24c5121 + b145d19 commit 468ded1
Show file tree
Hide file tree
Showing 13 changed files with 138 additions and 116 deletions.
7 changes: 6 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(PROJECT_NAME SocketForwarder)

project(${PROJECT_NAME} VERSION 0.1.1)
project(${PROJECT_NAME} VERSION 0.4.0)

ExternalProject_Add(CppSocketLibrary
GIT_REPOSITORY https://github.com/Kilemonn/Cpp-SocketLibrary.git
Expand All @@ -19,21 +19,26 @@ ExternalProject_Add(CppSocketLibrary
ExternalProject_Get_Property(CppSocketLibrary SOURCE_DIR)
set(SOCKET_LIB_SOURCE ${SOURCE_DIR})

find_package(log4cxx REQUIRED)

set(FORWARDER_SOURCE
socket-forwarder/main.cpp
socket-forwarder/environment/Environment.cpp
socket-forwarder/forwarder/Forwarder.cpp
socket-forwarder/sockets/Sockets.cpp
socket-forwarder/logger/Logger.cpp
)

add_executable(SocketForwarder ${FORWARDER_SOURCE})

target_include_directories(SocketForwarder
PUBLIC ${SOCKET_LIB_SOURCE}/src
${LOG4CXX_INCLUDE_DIRS}
)

target_link_libraries(SocketForwarder
PUBLIC ${SOCKET_LIB_SOURCE}/libCppSocketLibrary.a
PRIVATE log4cxx
pthread
bluetooth
uuid
Expand Down
4 changes: 3 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ WORKDIR /builder
# For alpine linux
# RUN apk update && apk upgrade && apk add g++ cmake make git bluez-dev glib-dev bluez gdb

RUN apt update && apt install g++ cmake make git libbluetooth-dev libglib2.0-dev bluez gdb uuid-dev -y
RUN apt update && apt install g++ cmake make git libbluetooth-dev libglib2.0-dev bluez gdb uuid-dev liblog4cxx-dev -y

COPY ./socket-forwarder ./socket-forwarder
COPY ./tests ./tests
Expand All @@ -39,6 +39,8 @@ WORKDIR /socket-forwarder
# For alpine linux
# RUN apk update && apk upgrade && apk add libstdc++

RUN apt update && apt install liblog4cxx-dev -y

COPY --from=builder /builder/build/SocketForwarder /socket-forwarder/SocketForwarder

ENTRYPOINT ["./SocketForwarder"]
8 changes: 0 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,6 @@ This will be the maximum read size for all TCP and UDP socket read operations.

---

#### socketforwarder.debug

*If not provided this is 'false' or disabled by default.*

This will enable more logging of messages received, timing taken to forward and the amount of clients in each forwarder group.

---

#### socketforwarder.host_address

*If not provided the value "0.0.0.0" is used.*
Expand Down
1 change: 0 additions & 1 deletion socket-forwarder/environment/Environment.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ namespace forwarder
const std::string HOST_ADDRESS = SOCKET_FORWARDER_PREFIX + "host_address";
const std::string NEW_CLIENT_PREFIX = SOCKET_FORWARDER_PREFIX + "new_client_prefix";
const std::string MAX_READ_IN_SIZE = SOCKET_FORWARDER_PREFIX + "max_read_in_size";
const std::string DEBUG = SOCKET_FORWARDER_PREFIX + "debug";

const std::string PRECONFIG_ADDRESSES_SUFFIX = "preconfig_addresses";
const std::string PORT_SUFFIX = "port";
Expand Down
108 changes: 37 additions & 71 deletions socket-forwarder/forwarder/Forwarder.cpp

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions socket-forwarder/forwarder/Forwarder.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@
#include <socket/TCPSocket.h>
#include <socket/UDPSocket.h>

#include <log4cxx/logger.h>

namespace forwarder
{

class Forwarder
{
protected:
Expand Down Expand Up @@ -41,10 +44,10 @@ namespace forwarder
std::optional<std::pair<std::thread, std::thread>> tcpRunningThreads = std::nullopt;
std::optional<std::pair<std::thread, std::thread>> udpRunningThreads = std::nullopt;

log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger("Forwarder");
bool forwarderIsRunning = false;
std::string newClientPrefix;
unsigned short maxReadInSize;
bool debug = false;

std::optional<kt::UDPSocket> udpRecieveSocket = std::nullopt;
std::optional<kt::ServerSocket> tcpServerSocket = std::nullopt;
Expand All @@ -62,7 +65,7 @@ namespace forwarder
void addSocketToTCPGroup(const std::string&, kt::TCPSocket);

public:
Forwarder(std::optional<kt::ServerSocket>, std::optional<kt::UDPSocket>, const std::string, const unsigned short, const bool);
Forwarder(std::optional<kt::ServerSocket>, std::optional<kt::UDPSocket>, const std::string, const unsigned short);

void preConfigureTCPAddress(const std::string&, kt::SocketAddress);
void addAddressToUDPGroup(kt::SocketAddress);
Expand Down
17 changes: 17 additions & 0 deletions socket-forwarder/logger/Logger.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#include "Logger.h"

#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/consoleappender.h>
#include <log4cxx/patternlayout.h>

namespace forwarder
{
void initialiseConsoleLogger()
{
log4cxx::PatternLayoutPtr patternLayout = std::make_shared<log4cxx::PatternLayout>();
patternLayout->setConversionPattern("%d{yyyy-MM-dd HH:mm:ss} [%-5p] %c{1}:%L - %m%n");
log4cxx::ConsoleAppenderPtr consoleAppender = std::make_shared<log4cxx::ConsoleAppender>(patternLayout);
log4cxx::BasicConfigurator::configure(consoleAppender);
}
}
6 changes: 6 additions & 0 deletions socket-forwarder/logger/Logger.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#pragma once

namespace forwarder
{
void initialiseConsoleLogger();
}
24 changes: 14 additions & 10 deletions socket-forwarder/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,36 @@
#include "sockets/Sockets.h"
#include "environment/Environment.h"
#include "forwarder/Forwarder.h"
#include "logger/Logger.h"


// Make sure version of built image matches
const std::string VERSION = "0.3.0";
const std::string VERSION = "0.4.0";

int main(int argc, char** argv)
{
std::cout << "Running SocketForwarder v" << VERSION << std::endl;
forwarder::initialiseConsoleLogger();

auto logger = log4cxx::Logger::getLogger("main");

LOG4CXX_INFO(logger, "Running SocketForwarder v" << VERSION);

const std::string newClientPrefix = forwarder::getEnvironmentVariableValueOrDefault(forwarder::NEW_CLIENT_PREFIX, forwarder::NEW_CLIENT_PREFIX_DEFAULT);
const unsigned short maxReadInSize = std::atoi(forwarder::getEnvironmentVariableValueOrDefault(forwarder::MAX_READ_IN_SIZE, std::to_string(forwarder::MAX_READ_IN_DEFAULT)).c_str());
const bool debug = forwarder::getEnvironmentVariableValue(forwarder::DEBUG).has_value();

std::cout << "Using new client prefix: [" << newClientPrefix << "].\n"
<< "Using max read in size: [" << maxReadInSize << "].\n"
<< "DEBUG flag set to [" << debug << "].\n"
<< "Binding to host address [" << forwarder::getEnvironmentVariableValueOrDefault(forwarder::HOST_ADDRESS, forwarder::HOST_ADDRESS_DEFAULT) << "]." << std::endl;
LOG4CXX_INFO(logger, "Using new client prefix: [" << newClientPrefix << "].");
LOG4CXX_INFO(logger, "Using max read in size: [" << maxReadInSize << "].");
LOG4CXX_INFO(logger, "Binding to host address [" << forwarder::getEnvironmentVariableValueOrDefault(forwarder::HOST_ADDRESS, forwarder::HOST_ADDRESS_DEFAULT) << "].");

std::optional<kt::ServerSocket> serverSocket = forwarder::setUpTcpServerSocket(argc > 1 ? std::make_optional(std::string(argv[1])) : std::nullopt);
std::optional<kt::UDPSocket> udpSocket = forwarder::setUpUDPSocket(argc > 2 ? std::make_optional(std::string(argv[2])) : std::nullopt);

forwarder::Forwarder forwarder(serverSocket, udpSocket, newClientPrefix, maxReadInSize, debug);
forwarder::Forwarder forwarder(serverSocket, udpSocket, newClientPrefix, maxReadInSize);

std::vector<kt::SocketAddress> udpPreconfiguredAddresses = forwarder::getPreconfiguredUDPAddresses();
if (!udpPreconfiguredAddresses.empty())
{
std::cout << "UDP preconfigured addresses provided, setting into forwarder..." << std::endl;
LOG4CXX_INFO(logger, "UDP preconfigured addresses provided, setting into forwarder...");
for (const kt::SocketAddress& addr : udpPreconfiguredAddresses)
{
forwarder.addAddressToUDPGroup(addr);
Expand All @@ -43,7 +47,7 @@ int main(int argc, char** argv)
std::unordered_map<std::string, std::vector<kt::SocketAddress>> tcpPreconfiguredAddresses = forwarder::getPreconfiguredTCPAddresses();
if (!tcpPreconfiguredAddresses.empty())
{
std::cout << "TCP preconfigured addresses provided, setting into forwarder..." << std::endl;
LOG4CXX_INFO(logger, "TCP preconfigured addresses provided, setting into forwarder...");
for (const auto& it : tcpPreconfiguredAddresses)
{
for (const kt::SocketAddress& addr : it.second)
Expand Down
38 changes: 21 additions & 17 deletions socket-forwarder/sockets/Sockets.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,19 @@
#include "../environment/Environment.h"
#include "Sockets.h"

#include <log4cxx/logger.h>

namespace forwarder
{
auto logger = log4cxx::Logger::getLogger("SocketForwarder");

std::optional<kt::ServerSocket> setUpTcpServerSocket(std::optional<std::string> defaultPort)
{
std::optional<std::string> tcpPort = forwarder::getEnvironmentVariableValue(forwarder::TCP_PORT);

if (!tcpPort.has_value() && !defaultPort.has_value())
{
std::cout << "Skipping TCP socket creation since value for [" + forwarder::TCP_PORT + "] was not provided." << std::endl;
LOG4CXX_INFO(logger, "Skipping TCP socket creation since value for [" + forwarder::TCP_PORT + "] was not provided.");
return std::nullopt;
}

Expand All @@ -28,12 +32,12 @@ namespace forwarder
}
catch(const kt::BindingException e)
{
std::cout << "[TCP] - Failed to bind server socket on port [" << portNumber << "]. " << e.what() << std::endl;
LOG4CXX_ERROR(logger, "[TCP] - Failed to bind server socket on port [" << portNumber << "]. " << e.what());
return std::nullopt;
}
catch (const kt::SocketException e)
{
std::cout << "[TCP] - Failed to create server socket: " << e.what() << std::endl;
LOG4CXX_ERROR(logger, "[TCP] - Failed to create server socket: " << e.what());
return std::nullopt;
}
}
Expand All @@ -44,7 +48,7 @@ namespace forwarder

if (!udpPort.has_value() && !defaultPort.has_value())
{
std::cout << "Skipping UDP socket creation since value for [" + forwarder::UDP_PORT + "] was not provided." << std::endl;
LOG4CXX_INFO(logger, "Skipping UDP socket creation since value for [" + forwarder::UDP_PORT + "] was not provided.");
return std::nullopt;
}

Expand All @@ -56,19 +60,19 @@ namespace forwarder
kt::UDPSocket udpSocket;
if (!udpSocket.bind(getEnvironmentVariableValueOrDefault(HOST_ADDRESS, HOST_ADDRESS_DEFAULT), portNumber).first)
{
std::cout << "[UDP] - Failed to bind to provided port [" << portNumber << "].\n";
LOG4CXX_ERROR(logger, "[UDP] - Failed to bind to provided port [" << portNumber << "].");
return std::nullopt;
}
return std::make_optional(udpSocket);
}
catch(const kt::BindingException e)
{
std::cout << "[UDP] - Failed to bind UDP socket on port: [" << portNumber << "]. " << e.what() << std::endl;
LOG4CXX_ERROR(logger, "[UDP] - Failed to bind UDP socket on port: [" << portNumber << "]. " << e.what());
return std::nullopt;
}
catch (const kt::SocketException e)
{
std::cout << "[UDP] - Failed to create UDP socket: " << e.what() << std::endl;
LOG4CXX_ERROR(logger, "[UDP] - Failed to create UDP socket: " << e.what());
return std::nullopt;
}
}
Expand All @@ -86,30 +90,30 @@ namespace forwarder
std::vector<std::string> parts = split(s, ":");
if (parts.size() == 1 && parts[0].empty())
{
// Skip
// Don't even log since its empty
}
else if (parts.size() < 3)
{
std::cout << "[TCP] - Unable to add address [" << s << "], expected format to be \"<groupId>:<address>:<port number>\"." << std::endl;
LOG4CXX_INFO(logger, "[TCP] - Unable to add address [" << s << "], expected format to be \"<groupId>:<address>:<port number>\".");
}
else
{
if (parts.size() > 3)
{
std::cout << "[TCP] - Multiple ':' provided in address string [" << s << "]. Attempting to parse and add address to group [" << parts[0] << "] using second and third elements as the address [" << parts[1] << ", " << parts[2] << "]." << std::endl;
LOG4CXX_INFO(logger, "[TCP] - Multiple ':' provided in address string [" << s << "]. Attempting to parse and add address to group [" << parts[0] << "] using second and third elements as the address [" << parts[1] << ", " << parts[2] << "].");
}

unsigned short portNumber = static_cast<unsigned short>(std::atoi(parts[2].c_str()));
addrinfo info = kt::createTcpHints();
std::pair<std::vector<kt::SocketAddress>, int> resolvedAddresses = kt::resolveToAddresses(parts[1], portNumber, info);
if (resolvedAddresses.first.empty())
{
std::cout << "[TCP] - Failed to resolve address [" << parts[1] << ":" << portNumber << "]. Address will not be added to TCP group [" << parts[0] << "]." << std::endl;
LOG4CXX_ERROR(logger, "[TCP] - Failed to resolve address [" << parts[1] << ":" << portNumber << "]. Address will not be added to TCP group [" << parts[0] << "].");
}
else
{
kt::SocketAddress addr = resolvedAddresses.first.at(0);
std::cout << "[TCP] - Resolved and added pre-configured address [" << kt::getAddress(addr).value_or("") + ":" + std::to_string(kt::getPortNumber(addr)) << "] to group [" << parts[0] << "]." << std::endl;
LOG4CXX_INFO(logger, "[TCP] - Resolved and added pre-configured address [" << kt::getAddress(addr).value_or("") + ":" + std::to_string(kt::getPortNumber(addr)) << "] to group [" << parts[0] << "].");

if (addresses.find(parts[0]) == addresses.end())
{
Expand Down Expand Up @@ -140,30 +144,30 @@ namespace forwarder
std::vector<std::string> parts = split(s, ":");
if (parts.size() == 1 && parts[0].empty())
{
// Skip
// Don't even log since its empty
}
else if (parts.size() < 2)
{
std::cout << "[UDP] - Unable to add address [" << s << "], expected format to be \"<address>:<port number>\"." << std::endl;
LOG4CXX_INFO(logger, "[UDP] - Unable to add address [" << s << "], expected format to be \"<address>:<port number>\".");
}
else
{
if (parts.size() > 2)
{
std::cout << "[UDP] - Multiple ':' provided in address string [" << s << "]. Attempting to parse as address using first two elements [" << parts[0] << ", " << parts[1] << "]." << std::endl;
LOG4CXX_INFO(logger, "[UDP] - Multiple ':' provided in address string [" << s << "]. Attempting to parse as address using first two elements [" << parts[0] << ", " << parts[1] << "].");
}

unsigned short portNumber = static_cast<unsigned short>(std::atoi(parts[1].c_str()));
addrinfo info = kt::createUdpHints();
std::pair<std::vector<kt::SocketAddress>, int> resolvedAddresses = kt::resolveToAddresses(parts[0], portNumber, info);
if (resolvedAddresses.first.empty())
{
std::cout << "[UDP] - Failed to resolve address [" << parts[0] << ":" << portNumber << "]. Address will not be added to UDP group." << std::endl;
LOG4CXX_ERROR(logger, "[UDP] - Failed to resolve address [" << parts[0] << ":" << portNumber << "]. Address will not be added to UDP group.");
}
else
{
kt::SocketAddress addr = resolvedAddresses.first.at(0);
std::cout << "[UDP] - Resolved and added pre-configured address [" << kt::getAddress(addr).value_or("") + ":" + std::to_string(kt::getPortNumber(addr)) << "] to UDP group." << std::endl;
LOG4CXX_INFO(logger, "[UDP] - Resolved and added pre-configured address [" << kt::getAddress(addr).value_or("") + ":" + std::to_string(kt::getPortNumber(addr)) << "] to UDP group.");
addresses.push_back(addr);
}
}
Expand Down
3 changes: 3 additions & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,14 @@ set(FORWARDER_SOURCE_FOR_TEST
../socket-forwarder/environment/Environment.cpp
../socket-forwarder/forwarder/Forwarder.cpp
../socket-forwarder/sockets/Sockets.cpp
../socket-forwarder/logger/Logger.cpp
)

add_executable(${PROJECT_NAME} ${FORWARDER_TEST_SOURCE} ${FORWARDER_SOURCE_FOR_TEST})

target_include_directories(SocketForwarderTests
PUBLIC ${SOCKET_LIB_SOURCE}/src
${LOG4CXX_INCLUDE_DIRS}
)

target_link_libraries(${PROJECT_NAME} PUBLIC
Expand All @@ -46,6 +48,7 @@ target_link_libraries(${PROJECT_NAME} PUBLIC
pthread
uuid
PUBLIC ${SOCKET_LIB_SOURCE}/libCppSocketLibrary.a
PRIVATE log4cxx
)

# Enable unit testing
Expand Down
15 changes: 13 additions & 2 deletions tests/socket-forwarder/forwarder/TCPSocketForwarderTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@

#include "../../../socket-forwarder/environment/Environment.h"
#include "../../../socket-forwarder/forwarder/Forwarder.h"
#include "../../../socket-forwarder/logger/Logger.h"

#include <log4cxx/basicconfigurator.h>

using namespace std::chrono_literals;

Expand All @@ -17,8 +20,16 @@ namespace forwarder
kt::ServerSocket serverSocket;
forwarder::Forwarder forwarder;
protected:
TCPSocketForwarderTest() : serverSocket(kt::SocketType::Wifi), forwarder(serverSocket, std::nullopt, NEW_CLIENT_PREFIX_DEFAULT, MAX_READ_IN_DEFAULT, true) {}
void SetUp() override
TCPSocketForwarderTest() : serverSocket(kt::SocketType::Wifi), forwarder(serverSocket, std::nullopt, NEW_CLIENT_PREFIX_DEFAULT, MAX_READ_IN_DEFAULT) {}

static void SetUpTestCase()
{
log4cxx::BasicConfigurator::resetConfiguration();
forwarder::initialiseConsoleLogger();
log4cxx::Logger::getRootLogger()->setLevel(log4cxx::Level::getDebug());
}

void SetUp() override
{
forwarder.start();
}
Expand Down
Loading

0 comments on commit 468ded1

Please sign in to comment.