diff --git a/ArgParser.hpp b/ArgParser.hpp new file mode 100644 index 0000000..ae65a25 --- /dev/null +++ b/ArgParser.hpp @@ -0,0 +1,82 @@ +#ifndef ARGPARSER_HPP +#define ARGPARSER_HPP + +#include +#include +#include +#include + +#include +#include + +// #include +// #include // move + +// #include "Singleton_DCLP.hpp" + +class ArgParser +{ +public: + ArgParser() : m_use_console(false), m_logFile() {} + void printUsage(bool cout = true) + { + std::ostringstream oss; + oss + << "Usage: cpplogger [OPTION]\n" + << "Logs the input to the console or to a file.\n" + << "\n" + << "Options:\n" + << " -c, log to console\n" + << " -f FILE log to FILE\n" + << " -h print this help\n" + << "\n" + << "Option -c and -f are mutually exclusive.\n" + << "\n" + << "Denes Matetelki \n"; + + if (cout) + std::cout << oss.str(); + else + std::cerr << oss.str(); + } + int parse(int argc, char* argv[]) + { + int c; + while ((c = getopt (argc, argv, "cf:h")) != -1) { + switch (c) { + case 'c': + m_use_console = true; + break; + case 'f': + m_logFile = std::string(optarg); + break; + case 'h': + printUsage(); + return EXIT_SUCCESS; + default: + printUsage(false); + return EXIT_FAILURE; + } + } + if ((m_use_console && !m_logFile.empty()) || + (!m_use_console && m_logFile.empty())) { + printUsage(false); + return EXIT_FAILURE; + } + return -1; + } + + bool useConsole() const { return m_use_console; } + std::string logFile() const { return m_logFile; } + +private: + int m_argc; + char** m_argv; + + bool m_use_console; + std::string m_logFile; +}; + +#define LOG *Logger::getInstance()->getStream() + +#endif // ARGPARSER_HPP diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..fba0a6d --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required (VERSION 3.10) +project (CppLogger) + +# Using Catch2's benchmarking tools +set(CATCH_HEADER_FILES Logger.hpp Singleton_DCLP.hpp ArgParser.hpp) +add_executable(cpplogger main.cpp ${HEADER_FILES}) + diff --git a/main.cpp b/main.cpp index a766323..ff26180 100644 --- a/main.cpp +++ b/main.cpp @@ -1,15 +1,36 @@ -#include +// #include #include +#include +#include "ArgParser.hpp" #include "Logger.hpp" -int main(int /*argc*/, char* /*argv*/[]) + +int main(int argc, char* argv[]) { - Logger::getInstance()->setStream(&std::cout); + ArgParser argparser; + const int r = argparser.parse(argc, argv); + if (r != -1) return r; + + std::ofstream logfile; + if (argparser.useConsole()) { + Logger::getInstance()->setStream(&std::cout); + } else { + logfile.open (argparser.logFile(), std::ios::out | std::ios::app); + if (!logfile.is_open()) { + std::cerr << "Could not open file '" << + argparser.logFile() << "' to append." << std::endl; + return EXIT_FAILURE; + } + Logger::getInstance()->setStream(&logfile); + } LOG << "hello" << std::endl; + if (!argparser.useConsole()) + logfile.close(); + return EXIT_SUCCESS; }