-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLog.cpp
108 lines (78 loc) · 2.31 KB
/
Log.cpp
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include "stdafx.h"
#include "Log.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#endif
namespace Log
{
const int MAX_BUF_SIZE = 4096;
const int HOUR = 60*60;
const int DAY = HOUR * 24;
static CString _carrige_return = _T("\r\n");
static CString _log_file_name_format = _T("%Y-%m-%d.txt");
static CString _log_time_format = _T("[%Y-%m-%d %H:%M:%S] ");
namespace
{
CString _loot_dir;
CRITICAL_SECTION cs_;
CTime _last_clean;
};
void Init()
{
InitializeCriticalSectionAndSpinCount( &cs_ , 3000 );
SetDirectory( FolderUtil::GetFullDirectoryPath() + _T("Log\\") );
}
void Release()
{
DeleteCriticalSection( &cs_ );
}
void SetDirectory( LPCTSTR Dir )
{
CSPtr RAII( cs_ );
if ( !FolderUtil::ExistFolder( Dir ) )
FolderUtil::CreateFolder( Dir , FALSE );
_loot_dir = Dir;
TCHAR last_ch = _loot_dir.GetAt( _loot_dir.GetLength() - 1 );
if ( last_ch != _T('\\') ) _loot_dir.AppendChar( _T('\\') );
}
void CleanLogFile( int MaintainDay )
{
Second Gap = Time::SubtractFromNow( _last_clean );
if ( Gap <= (HOUR*24) ) return;
CTime BeforeDay = Time::AddSec( CTime::GetCurrentTime() , -(DAY * MaintainDay) );
FolderUtil::Search( _loot_dir , _T("txt") , [&]( const WIN32_FIND_DATA& Info )
{
if ( Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) return TRUE;
CTime LastWriteFileTime = CTime(Info.ftLastWriteTime);
if ( BeforeDay > LastWriteFileTime )
File::Delete( _loot_dir + Info.cFileName );
return TRUE;
});
_last_clean = CTime::GetCurrentTime();
}
void Log( LPCTSTR LogText , va_list ap )
{
CSPtr RAII( cs_ );
CTime Now = CTime::GetCurrentTime();
CleanLogFile( 30 );
TCHAR buffer[MAX_BUF_SIZE] = { 0 , };
_vstprintf_s( buffer , LogText , ap );
CString LogTime = Now.Format( _log_time_format );
CString FileName = Now.Format( _log_file_name_format );
CString LogFullPath = _loot_dir + FileName;
FolderUtil::CreateFolder( _loot_dir , FALSE );
HandlePtr Handle = File::GetHandle( LogFullPath );
CStringA Log;
Log.Format( "%s%s\r\n" , (CStringA)LogTime , (CStringA)buffer );
File::WriteLn( Handle.Get() , (LPBYTE)(LPCSTR)Log , Log.GetLength() , NULL );
}
void Write( LPCTSTR Text , ... )
{
va_list ap = NULL;
va_start( ap , Text );
Log( Text , ap );
va_end( ap );
}
};