I am working on a project in C under a Linux environment and I'm looking for an efficient way to add errors to a log file. I tried to use Syslog with the following initialization:
setlogmask(LOG_UPTO(7));
openlog(name, LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER);
But it seems that it works too slow. I need it to work very fast.. Can someone help with that? Maybe the syslog is not the right approach.
You can write a custom light weight logger or may 3rd party open source one...
For example 3rd part C++ logger [ http://logging.apache.org/log4cxx/]
And Here is simple [buggy] custom logger [ From book C++ Timesaving Techniques For Dummies ]
#ifndef __SimpleLogger__
#define __SimpleLogger__
#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdarg.h>
#include <fstream>
using namespace std;
class SimpleLogger
{
public:
SimpleLogger( void )
{
bOn = false;
bForceFlush = false;
}
SimpleLogger( const char *strFileName )
{
sFileName = strFileName;
bOn = false;
bForceFlush = false;
}
SimpleLogger( const SimpleLogger& aCopy )
{
sFileName = aCopy.sFileName;
bForceFlush = aCopy.bForceFlush;
setOn( aCopy.bOn );
}
virtual ~SimpleLogger()
{
Flush();
if ( bOn )
file.close();
}
void setOn( bool flag )
{
bOn = flag;
if ( bOn )
{
file.open( sFileName.c_str() ,fstream::in | fstream::out | fstream::app);
}
}
bool getOn( void )
{
return bOn;
}
void setForceFlush( bool flag )
{
bForceFlush = flag;
}
bool getForceFlush( void )
{
return bForceFlush;
}
void setFileName ( const char
*strFileName )
{
sFileName = strFileName;
}
string getFileName ( void )
{
return sFileName;
}
void Log( const char *strMessage )
{
sMessage += strMessage;
sMessage += "\n";
if ( bForceFlush )
Flush();
}
void LogString( const char *fmt, ... )
{
char szBuffer[256];
va_list marker;
va_start( marker, fmt );
vsprintf(szBuffer, fmt, marker );
sMessage += szBuffer;
sMessage += "\n";
if ( bForceFlush )
Flush();
}
void Flush( void )
{
if ( bOn )
file << sMessage << endl;
sMessage = "";
}
private:
bool bOn;
bool bForceFlush;
string sMessage;
string sFileName;
ofstream file;
};
#endif
Usage :
SimpleLogger logger("MyLog.txt");
logger.setForceFlush( true );
logger.setOn(true);
logger.Log("I am the buggy logger");
Warning: This is "toy" logger with some bugs to just give you some idea about custom logger...Do not use directly in real applications..