#include "FileLogSink.hpp" #include #include #ifndef _WIN32 #include #else #define WIN32_MEAN_AND_LEAN #include #endif using namespace std; #ifndef _WIN32 static string timestamp( ) { time_t t; time( &t ); struct tm r; memset( &r, 0, sizeof( r ) ); localtime_r( &t, &r ); char buf[30]; strftime( buf, sizeof( buf ), "%F - %X", &r ); struct timeval tv; gettimeofday( &tv, 0 ); char result[100]; snprintf( result, sizeof( result ), "%s.%03ld", buf, (long)tv.tv_usec / 1000 ); return result; } #else static string timestamp( ) { enum { LEN = 255 }; char buf[LEN]; if( GetTimeFormat( LOCALE_USER_DEFAULT, 0, 0, "HH':'mm':'ss", buf, LEN ) == 0 ) { return ""; } static DWORD first = GetTickCount( ); char result[LEN] = { 0 }; _snprintf( result, LEN, "%s.%03ld", buf, (long)( GetTickCount( ) - first ) % 1000 ); return result; } #endif FileLogSink::FileLogSink( const LogLevel level, const string &filename ) : LogSink( level ), m_filename( filename ) { m_file.exceptions( m_file.badbit | m_file.failbit ); try { m_file.open( m_filename.c_str( ), std::ios::app ); } catch( exception &e ) { LOG( logCRITICAL ) << e.what( ); } } FileLogSink::~FileLogSink( ) { m_file.close( ); } void FileLogSink::log( const LogLevel level, const string &msg ) { if( level > reportingLevel( ) ) return; m_file << timestamp( ) << " " << Logger::toString( level ) << ": " << msg << endl; }