master
denes 5 years ago
parent 465e7f8b6a
commit 09a71bb1a9
Signed by: denes
GPG Key ID: A7D50EAD42F9FC9F

@ -0,0 +1,82 @@
#ifndef ARGPARSER_HPP
#define ARGPARSER_HPP
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <sstream>
// #include <ostream>
// #include <utility> // 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 <denes@matetelki.com>\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

@ -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})

@ -1,15 +1,36 @@
#include <cstdlib>
// #include <cstdlib>
#include <iostream>
#include <fstream>
#include "ArgParser.hpp"
#include "Logger.hpp"
int main(int /*argc*/, char* /*argv*/[])
int main(int argc, char* argv[])
{
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;
}

Loading…
Cancel
Save