#include "StdAfx.h"
#include "logwriter.h"
#include "dir.h"
#include "dateutility.h"
#include "server.h"

CLogWriter::CLogWriter(void)
{
}

CLogWriter::~CLogWriter(void)
{
}

//	ログをファイルに出力
void CLogWriter::UpdateLog()
{
	SCOPE_LOCK();

	//	ノーマルログ
	if(m_normalLog.GetSize() > 0)
	{
		CString	logPath = m_server->m_setting.GetConfig("Log::LogFilePath","%ServerRoot%Logs\\%Year%%Month%%Day%.txt");
		CDir::MakeAllDirectory(CDir::PathToDir(logPath));

		FILE	*logWriter;
		if(!fopen_s(&logWriter, logPath,"at"))
		{
			for(int i=0;i<m_normalLog.GetSize();i++)
				fputs(m_normalLog[i] + "\n",logWriter);
			fclose(logWriter);
		}

		m_normalLog.RemoveAll();
	}

	//	システムログ
	if(m_systemLog.GetSize() > 0)
	{
		//	ログパスの取得
		CString	logPath = m_server->m_setting.GetConfig("Log::SystemLogFilePath","%ServerRoot%Logs\\SystemLog.txt");
		CDir::MakeAllDirectory(CDir::PathToDir(logPath));

		FILE	*logWriter;
		if(!fopen_s(&logWriter, logPath,"at"))
		{
			for(int i=0;i<m_systemLog.GetSize();i++)
				fputs(m_systemLog[i] + "\n",logWriter);
			fclose(logWriter);
		}

		m_systemLog.RemoveAll();
	}
}


/*!
 *	ログの出力
 *
 *	@param lpszFormat	書式
 */
void CLogWriter::WriteLog(LPCTSTR lpszFormat, ...)
{
	SCOPE_LOCK();

	//	書式展開
	va_list argList;
	CString	str;
	va_start(argList, lpszFormat);
	str.FormatV(lpszFormat,argList);
	va_end(argList);

	m_normalLog.Add(str);
}



/*!
 *	システムログの出力
 *
 *	@param lpszFormat	書式
 */
void CLogWriter::WriteSystemLog(LPCTSTR lpszFormat, ...)
{
	SCOPE_LOCK();

	//	書式展開
	va_list argList;
	CString	str;
	va_start(argList, lpszFormat);
	str.FormatV(lpszFormat,argList);
	va_end(argList);


	//	ログ出力
	CTime	time=CTime::GetCurrentTime();
	CString	ts = time.Format("[%Y/%m/%d %H:%M:%S]") + str;

	m_systemLog.Add(ts);
}
