欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++实现简单日志类

程序员文章站 2022-06-03 10:01:45
...

一个简单的记录日志至文件或者(标准输出及错误文件),不包括系统日志。

直接上代码:

LogFile.h

#ifndef LOG_FILE_INC
#define LOG_FILE_INC

class LogFile
{
public:
   LogFile() ;
   virtual ~LogFile() ;

   static void open( const char *logFName_ ) ;
   static void close() ;
   static void puts( const char *str ) ;
   static void date( const char *prefixStr ) ;
   static void hostname( const char *prefixStr ) ;
   static void printf( const char *msg , ... ) ;
   static FILE *getFD() { return outFD ; } ;

private:
   static char        *logFName ;
   static FILE        *outFD ;
};

#endif

LogFile.cpp

#include "LogFile.h"
#include "time.h"
#include "unistd.h"

FILE *LogFile::outFD = NULL ;
char *LogFile::logFName = NULL ;


LogFile::LogFile()
{
}


LogFile::~LogFile()
{
}

void LogFile::open( const char *logFName_ )
{
   if ( outFD != NULL )
      error("LogFile::open - outFD != NULL. File already open.") ;

   if ( (logFName_ == NULL) || (logFName_[0] == '\0') )
      return ;

   if ( strcmp( logFName_ , "stdout" ) == 0 )
      outFD = stdout ;
   else if ( strcmp( logFName_ , "stderr" ) == 0 )
      outFD = stderr ;
   else
   {
      logFName = new char[strlen(logFName_)+1] ;
      strcpy( logFName , logFName_ ) ;

      if ( (outFD = fopen( logFName , "wb" )) == NULL )
         error("LogFile::init - error opening log file: %s" , logFName) ;
   }
}


void LogFile::close()
{
   if ( (outFD != NULL) && (outFD != stdout) && (outFD != stderr) )
      fclose( outFD ) ;
   outFD = NULL ;
   delete [] logFName ;
   logFName = NULL ;
}

void LogFile::puts( const char *str )
{
   if ( outFD == NULL )
      return ;

   if ( (str == NULL) || (str[0] == '\0') )
      error("LogFile::puts - str undefined") ;

   fputs( str , outFD ) ;
   fflush( outFD ) ;
}


void LogFile::date( const char *prefixStr )
{
   if ( outFD == NULL )
      return ;

   if ( prefixStr != NULL )
   {
      fprintf( outFD , "%s " , prefixStr ) ;
   }

   time_t t = time(NULL) ;
   fputs( ctime( &t ) , outFD ) ;
   fflush( outFD ) ;
}

void LogFile::hostname( const char *prefixStr )
{
   if ( outFD == NULL )
      return ;

   if ( prefixStr != NULL )
   {
      fprintf( outFD , "%s " , prefixStr ) ;
   }

   char str[100] ;
   if ( gethostname( str , 100 ) < 0 )
   {
      fprintf( outFD , "UNKNOWN HOST\n" ) ;
   }
   else
   {
      fprintf( outFD , "%s\n" , str ) ;
   }
   fflush( outFD ) ;
}


void LogFile::printf( const char *msg , ... )
{
   if ( outFD == NULL )
      return ;

   va_list args ;
   va_start( args , msg ) ;
   vfprintf( outFD , msg , args ) ;
   va_end(args);
   fflush( outFD ) ;
}