Logger.h
/*
Basic Header-Only Logging Class
Copyright (C) 2019 Ruven Pillay
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _LOGGER_H
#define _LOGGER_H
#include <ostream>
#include <fstream>
#include <streambuf>
#include <string>
#ifdef HAVE_SYSLOG_H
#include <syslog.h>
class SyslogStream : public std::streambuf {
private:
std::string _buf;
int _level;
public:
SyslogStream() : _level( LOG_DEBUG ) { };
void open(){
openlog( "iipsrv", LOG_NDELAY, LOG_USER );
}
void close(){ closelog(); };
int sync(){
if (_buf.size()) {
syslog( _level, "%s", _buf.c_str() );
_buf.erase();
}
return 0;
}
int_type overflow( int_type c ){
if( c == traits_type::eof() ) sync();
else _buf += static_cast<char>(c);
return c;
}
};
#endif
class Logger : public std::ostream {
private:
#ifdef HAVE_SYSLOG_H
SyslogStream _syslogStream;
#endif
std::ofstream _fstream;
enum Type {
#ifdef HAVE_SYSLOG_H
SYSLOG,
#endif
FILE
};
Type _type;
public:
Logger() : std::ostream( NULL ) {};
~Logger() { this->close(); };
void open( std::string file ){
#ifdef HAVE_SYSLOG_H
// Open a syslog connection - assign syslog stream to our stream buffer
if( file == "syslog" ){
_type = SYSLOG;
this->rdbuf( &_syslogStream );
_syslogStream.open();
}
// Create an output file stream and assign it to our stream buffer
else{
#endif
_type = FILE;
_fstream.open( file.c_str(), ios_base::app );
std::streambuf *buffer = _fstream.rdbuf();
this->rdbuf( buffer );
#ifdef HAVE_SYSLOG_H
}
#endif
};
void close(){
switch( _type ){
#ifdef HAVE_SYSLOG_H
case SYSLOG:
_syslogStream.close();
break;
#endif
default:
_fstream.close();
}
};
std::string types(){
std::string types = "file";
#ifdef HAVE_SYSLOG_H
types += ", syslog";
#endif
return types;
};
};
#endif
Logger::types
std::string types()
Provide a list of available logging types.
Definition Logger.h:153
Logger::open
void open(std::string file)
Open our logging output.
Definition Logger.h:114
Logger::Logger
Logger()
Constructor - derived from std::ostream.
Definition Logger.h:104
Logger::~Logger
~Logger()
Destructor - close our logging stream.
Definition Logger.h:108
Logger::close
void close()
Close depending on type.
Definition Logger.h:137