#include "stdafx.h"
#include "Logger.h"

Logger::Logger( const std::string &file )
{
    InitializeCriticalSectionEx( &m_critSec, 0, 0 );
	m_pFile = fopen( file.c_str(), "w" );
}

Logger::~Logger()
{
    DeleteCriticalSection( &m_critSec );
	fclose( m_pFile );
}

void Logger::WriteLine( const char *msg )
{
    if( !m_pFile )
        return;

	EnterCriticalSection( &m_critSec );
	fprintf( m_pFile, "%s", msg );
	fflush( m_pFile );
	LeaveCriticalSection( &m_critSec );
}

void Logger::Write( const char *fmt, ... )
{
	char szBuf[512];
	memset( szBuf, 0, 512 * sizeof( char ) );

    try
    {
        int nSize = 0;

        va_list args;
        va_start( args, fmt );
		nSize = vsnprintf ( szBuf, 512, fmt, args ); // C4996
        va_end( args );

        WriteLine( szBuf );
    }
    catch( ... )
    {
        WriteLine( "Exception" );
    }
}

void Logger::GetCurrentDateTime( char* buffer, int size )
{
    time_t now = time( 0 );
    struct tm tstruct;
    localtime_s( &tstruct, &now );
    strftime( buffer, size, "%Y-%m-%d.%X", &tstruct );
}
