summaryrefslogtreecommitdiff
path: root/src/liblogger/FileLogSink.cpp
blob: d812dbed529a578e58190279df1c62d4794737d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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;
}