summaryrefslogtreecommitdiff
path: root/src/liblogger/FileLogSink.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/liblogger/FileLogSink.cpp')
-rw-r--r--src/liblogger/FileLogSink.cpp85
1 files changed, 85 insertions, 0 deletions
diff --git a/src/liblogger/FileLogSink.cpp b/src/liblogger/FileLogSink.cpp
new file mode 100644
index 0000000..d812dbe
--- /dev/null
+++ b/src/liblogger/FileLogSink.cpp
@@ -0,0 +1,85 @@
+#include "FileLogSink.hpp"
+
+#include <iostream>
+#include <cstring>
+
+#ifndef _WIN32
+#include <sys/time.h>
+#else
+#define WIN32_MEAN_AND_LEAN
+#include <windows.h>
+#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 "<timestamp error>";
+ }
+
+ 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;
+}