You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.0 KiB

5 years ago
#ifndef ARGPARSER_HPP
#define ARGPARSER_HPP
#include <unistd.h>
#include <iostream>
#include <sstream>
class ArgParser
{
public:
5 years ago
ArgParser()
: m_print_to_console(false)
, m_logFile()
5 years ago
, m_timestamp(false)
, m_hostname(false)
, m_username(false)
5 years ago
{}
5 years ago
void printUsage(bool cout = true)
{
std::ostringstream oss;
oss
<< "Usage: cpplogger [OPTION]\n"
5 years ago
<< "Logs the input (till EOF) to the console or to a file.\n"
5 years ago
<< "\n"
<< "Options:\n"
<< " -c, log to console\n"
<< " -f FILE log to FILE\n"
5 years ago
<< " -t, prefix lines with timestamp\n"
<< " -n, prefix lines with hostname\n"
<< " -u, prefix lines with user name\n"
5 years ago
<< " -h print this help\n"
<< "\n"
5 years ago
<< "Option -c and -f are mutually exclusive, specify one.\n"
5 years ago
<< "\n"
<< "Denes Matetelki <denes@matetelki.com>\n";
if (cout)
std::cout << oss.str();
else
std::cerr << oss.str();
}
5 years ago
5 years ago
int parse(int argc, char* argv[])
{
int c;
5 years ago
while ((c = getopt (argc, argv, "cf:tnuh")) != -1) {
5 years ago
switch (c) {
case 'c':
5 years ago
m_print_to_console = true;
break;
case 'f':
m_logFile = std::string(optarg);
break;
5 years ago
case 't':
5 years ago
m_timestamp = true;
5 years ago
break;
case 'u':
m_username = true;
5 years ago
break;
case 'h':
printUsage();
return EXIT_SUCCESS;
default:
printUsage(false);
return EXIT_FAILURE;
}
}
5 years ago
if ((m_print_to_console && !m_logFile.empty()) ||
(!m_print_to_console && m_logFile.empty())) {
5 years ago
printUsage(false);
return EXIT_FAILURE;
}
return -1;
}
5 years ago
bool printToConsole() const { return m_print_to_console; }
5 years ago
bool printTimestamp() const { return m_timestamp; }
bool printHostname() const { return m_hostname; }
bool printUsername() const { return m_username; }
5 years ago
std::string logFile() const { return m_logFile; }
private:
int m_argc;
char** m_argv;
5 years ago
bool m_print_to_console;
5 years ago
std::string m_logFile;
5 years ago
bool m_timestamp;
bool m_hostname;
bool m_username;
5 years ago
};
5 years ago
// #define LOG *Logger::getInstance()->getStream()
5 years ago
#endif // ARGPARSER_HPP