forked from keizi666/charu3
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlog.cpp
90 lines (75 loc) · 2.22 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
#include "stdafx.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#define new DEBUG_NEW
#endif
#include <stdarg.h>
#include "log.h"
namespace{
CString getDateTimeString()
{
time_t long_time;
time(&long_time);
struct tm newtime;
localtime_s(&newtime, &long_time);
CString strDate;
strDate.Format(_T("%.4d/%.2d/%.2d %.2d:%.2d:%.2d"),
newtime.tm_year + 1900,
newtime.tm_mon + 1,
newtime.tm_mday,
newtime.tm_hour,
newtime.tm_min,
newtime.tm_sec);
return strDate;
}
} // anonymous namespace
Logger::Logger() : m_logFilePath(nullptr)
{
}
Logger::~Logger()
{
if (m_logFilePath) {
delete[] m_logFilePath;
m_logFilePath = nullptr;
}
}
void Logger::SetLogFile(const CString& strPath)
{
if (m_logFilePath) {
delete[] m_logFilePath;
m_logFilePath = nullptr;
}
int pathSize = ::WideCharToMultiByte(CP_ACP, 0, strPath, -1, NULL, 0, NULL, NULL);
m_logFilePath = new char[pathSize + 1];
if (m_logFilePath) {
::WideCharToMultiByte(CP_ACP, 0, strPath, -1, m_logFilePath, pathSize, "", NULL);
m_logFilePath[pathSize] = NULL;
}
}
void Logger::WriteLog(const CString& strSourceFile, int nSourceLine, const CString strFormat, ...)
{
CString str;
va_list args;
va_start(args, strFormat);
str.FormatV(strFormat, args);
va_end(args);
CString strWrite;
strWrite.Format(_T("%s %s [%s:%d]\n"), getDateTimeString().GetString(), str.GetString(), strSourceFile.GetString(), nSourceLine);
OutputDebugString(strWrite);
if (m_logFilePath) {
FILE* outPut = nullptr;
if (fopen_s(&outPut, m_logFilePath, "a") == 0) {
int nDataSize = ::WideCharToMultiByte(CP_ACP, 0, strWrite, -1, NULL, 0, NULL, NULL);
char* szMbcsBuff = new char[nDataSize + 1];
if (szMbcsBuff) {
::WideCharToMultiByte(CP_ACP, 0, strWrite, -1, szMbcsBuff, nDataSize, "", NULL);
szMbcsBuff[nDataSize] = NULL;
fputs(szMbcsBuff, outPut);
delete[] szMbcsBuff;
}
fclose(outPut);
}
}
}
Logger gLogger;