SimpleLog.h 10.4 KB
Newer Older
1
2
3
4
5
6
// 简易日志

#ifndef __SIMPLE_LOG_H__
#define __SIMPLE_LOG_H__

#include <time.h>
liucong's avatar
liucong committed
7

8
9
#include <map>
#include <mutex>
liucong's avatar
liucong committed
10
11
12
13
#include <string>
#include <thread>

#if(defined WIN32 || defined _WIN32)
14
15
16
17
18
19
20
21
#include <Windows.h>
#else
#include <sys/time.h>
#endif

using namespace std;

/** 简易日志
liucong's avatar
liucong committed
22
 *
liucong's avatar
liucong committed
23
 * 不依赖于其他第三方库,只需要包含一个头文件就可以使用。提供了4种日志级别,包括INFO,DEBUG,WARN和ERROR。
liucong's avatar
liucong committed
24
 *
25
 * 示例1:
liucong's avatar
liucong committed
26
27
    //
 初始化日志,在./Log/目录下创建两个日志文件log1.log和log2.log(注意:目录./Log/需要存在,否则日志创建失败)
28
29
30
31
32
    LogManager::GetInstance()->Initialize("./Log/","log1");
    LogManager::GetInstance()->Initialize("./Log/","log2");

    // 写日志
    string log = "Hello World";
liucong's avatar
liucong committed
33
34
35
36
    LOG_INFO(LogManager::GetInstance()->GetLogFile("log1"), "%s\n",
 log.c_str()); // 写入log1.log
    LOG_INFO(LogManager::GetInstance()->GetLogFile("log2"), "%s\n",
 log.c_str()); // 写入log2.log
37
38
39
40

    // 关闭日志
    LogManager::GetInstance()->Close("log1");
    LogManager::GetInstance()->Close("log2");
liucong's avatar
liucong committed
41

42
43
44
  * 示例2:
    // 将日志输出到控制台
    string log = "Hello World";
liucong's avatar
liucong committed
45
    LOG_INFO(stdout, "%s\n", log.c_str());
46
47
48
49
50
51
52
53
54
55
56

  * 注意:
    1. 需要C++11
    2. 多线程的时候需要加锁(打开#define LOG_MUTEX),否则会导致日志显示混乱

*/

// #define LOG_MUTEX  // 加锁

class LogManager
{
liucong's avatar
liucong committed
57
58
    private:
    LogManager() {}
59

liucong's avatar
liucong committed
60
61
62
    public:
    ~LogManager() {}
    inline void Initialize(const string& parentPath, const string& logName)
63
64
    {
        // 日志名为空表示输出到控制台
liucong's avatar
liucong committed
65
        if(logName.size() == 0)
66
67
68
69
            return;

        // 查找该日志文件,如果没有则创建
        std::map<string, FILE*>::const_iterator iter = logMap.find(logName);
liucong's avatar
liucong committed
70
        if(iter == logMap.end())
71
        {
liucong's avatar
liucong committed
72
73
74
            string pathOfLog = parentPath + logName + ".log";
            FILE* logFile    = fopen(pathOfLog.c_str(), "a"); // w:覆盖原有文件,a:追加
            if(logFile != NULL)
75
76
77
78
79
            {
                logMap.insert(std::make_pair(logName, logFile));
            }
        }
    }
liucong's avatar
liucong committed
80
    inline FILE* GetLogFile(const string& logName)
81
    {
liucong's avatar
liucong committed
82
83
        std::map<string, FILE*>::const_iterator iter = logMap.find(logName);
        if(iter == logMap.end())
84
85
86
87
88
89
        {
            return NULL;
        }

        return (*iter).second;
    }
liucong's avatar
liucong committed
90
    inline void Close(const string& logName)
91
    {
liucong's avatar
liucong committed
92
93
        std::map<string, FILE*>::const_iterator iter = logMap.find(logName);
        if(iter == logMap.end())
94
95
96
97
98
99
100
        {
            return;
        }

        fclose((*iter).second);
        logMap.erase(iter);
    }
liucong's avatar
liucong committed
101
    inline std::mutex& GetLogMutex() { return logMutex; }
102
103
104
105
106
107
108

    // Singleton
    static LogManager* GetInstance()
    {
        static LogManager logManager;
        return &logManager;
    }
liucong's avatar
liucong committed
109
110

    private:
111
112
113
114
115
    std::map<string, FILE*> logMap;
    std::mutex logMutex;
};

#ifdef LOG_MUTEX
liucong's avatar
liucong committed
116
117
#define LOCK LogManager::GetInstance()->GetLogMutex().lock()
#define UNLOCK LogManager::GetInstance()->GetLogMutex().unlock()
118
#else
liucong's avatar
liucong committed
119
120
#define LOCK
#define UNLOCK
121
122
123
#endif

// log time
liucong's avatar
liucong committed
124
typedef struct _LogTime
125
126
127
128
129
130
131
132
133
134
{
    string year;
    string month;
    string day;
    string hour;
    string minute;
    string second;
    string millisecond; // ms
    string microsecond; // us
    string weekDay;
liucong's avatar
liucong committed
135
} LogTime;
136
137
138
139
140

inline LogTime GetTime()
{
    LogTime currentTime;

liucong's avatar
liucong committed
141
#if(defined WIN32 || defined _WIN32)
142
143
144
    SYSTEMTIME systemTime;
    GetLocalTime(&systemTime);

liucong's avatar
liucong committed
145
    char temp[8] = {0};
146
    sprintf(temp, "%04d", systemTime.wYear);
liucong's avatar
liucong committed
147
    currentTime.year = string(temp);
148
    sprintf(temp, "%02d", systemTime.wMonth);
liucong's avatar
liucong committed
149
    currentTime.month = string(temp);
150
    sprintf(temp, "%02d", systemTime.wDay);
liucong's avatar
liucong committed
151
    currentTime.day = string(temp);
152
    sprintf(temp, "%02d", systemTime.wHour);
liucong's avatar
liucong committed
153
    currentTime.hour = string(temp);
154
    sprintf(temp, "%02d", systemTime.wMinute);
liucong's avatar
liucong committed
155
    currentTime.minute = string(temp);
156
    sprintf(temp, "%02d", systemTime.wSecond);
liucong's avatar
liucong committed
157
    currentTime.second = string(temp);
158
    sprintf(temp, "%03d", systemTime.wMilliseconds);
liucong's avatar
liucong committed
159
    currentTime.millisecond = string(temp);
160
    sprintf(temp, "%d", systemTime.wDayOfWeek);
liucong's avatar
liucong committed
161
    currentTime.weekDay = string(temp);
162
#else
liucong's avatar
liucong committed
163
164
    struct timeval tv;
    struct tm* p;
165
166
167
    gettimeofday(&tv, NULL);
    p = localtime(&tv.tv_sec);

liucong's avatar
liucong committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    char temp[8] = {0};
    sprintf(temp, "%04d", 1900 + p->tm_year);
    currentTime.year = string(temp);
    sprintf(temp, "%02d", 1 + p->tm_mon);
    currentTime.month = string(temp);
    sprintf(temp, "%02d", p->tm_mday);
    currentTime.day = string(temp);
    sprintf(temp, "%02d", p->tm_hour);
    currentTime.hour = string(temp);
    sprintf(temp, "%02d", p->tm_min);
    currentTime.minute = string(temp);
    sprintf(temp, "%02d", p->tm_sec);
    currentTime.second = string(temp);
    sprintf(temp, "%03d", (int)(tv.tv_usec / 1000));
182
183
184
185
186
187
188
189
190
    currentTime.millisecond = string(temp);
    sprintf(temp, "%03d", (int)(tv.tv_usec % 1000));
    currentTime.microsecond = string(temp);
    sprintf(temp, "%d", p->tm_wday);
    currentTime.weekDay = string(temp);
#endif
    return currentTime;
}

liucong's avatar
liucong committed
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#define LOG_TIME(logFile)                               \
    do                                                  \
    {                                                   \
        LogTime currentTime = GetTime();                \
        fprintf(((logFile == NULL) ? stdout : logFile), \
                "%s-%s-%s %s:%s:%s.%s\t",               \
                currentTime.year.c_str(),               \
                currentTime.month.c_str(),              \
                currentTime.day.c_str(),                \
                currentTime.hour.c_str(),               \
                currentTime.minute.c_str(),             \
                currentTime.second.c_str(),             \
                currentTime.millisecond.c_str());       \
    } while(0)
205

liucong's avatar
liucong committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#define LOG_INFO(logFile, logInfo, ...)                                          \
    do                                                                           \
    {                                                                            \
        LOCK;                                                                    \
        LOG_TIME(logFile);                                                       \
        fprintf(((logFile == NULL) ? stdout : logFile), "INFO\t");               \
        fprintf(((logFile == NULL) ? stdout : logFile),                          \
                "[%s:%d (%s) ]: ",                                               \
                __FILE__,                                                        \
                __LINE__,                                                        \
                __FUNCTION__);                                                   \
        fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
        fflush(logFile);                                                         \
        UNLOCK;                                                                  \
    } while(0)

#define LOG_DEBUG(logFile, logInfo, ...)                                         \
    do                                                                           \
    {                                                                            \
        LOCK;                                                                    \
        LOG_TIME(logFile);                                                       \
        fprintf(((logFile == NULL) ? stdout : logFile), "DEBUG\t");              \
        fprintf(((logFile == NULL) ? stdout : logFile),                          \
                "[%s:%d (%s) ]: ",                                               \
                __FILE__,                                                        \
                __LINE__,                                                        \
                __FUNCTION__);                                                   \
        fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
        fflush(logFile);                                                         \
        UNLOCK;                                                                  \
    } while(0)

#define LOG_ERROR(logFile, logInfo, ...)                                         \
    do                                                                           \
    {                                                                            \
        LOCK;                                                                    \
        LOG_TIME(logFile);                                                       \
        fprintf(((logFile == NULL) ? stdout : logFile), "ERROR\t");              \
        fprintf(((logFile == NULL) ? stdout : logFile),                          \
                "[%s:%d (%s) ]: ",                                               \
                __FILE__,                                                        \
                __LINE__,                                                        \
                __FUNCTION__);                                                   \
        fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
        fflush(logFile);                                                         \
        UNLOCK;                                                                  \
    } while(0)
253

liucong's avatar
liucong committed
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#define LOG_WARN(logFile, logInfo, ...)                                          \
    do                                                                           \
    {                                                                            \
        LOCK;                                                                    \
        LOG_TIME(logFile);                                                       \
        fprintf(((logFile == NULL) ? stdout : logFile), "WARN\t");               \
        fprintf(((logFile == NULL) ? stdout : logFile),                          \
                "[%s:%d (%s) ]: ",                                               \
                __FILE__,                                                        \
                __LINE__,                                                        \
                __FUNCTION__);                                                   \
        fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
        fflush(logFile);                                                         \
        UNLOCK;                                                                  \
    } while(0)

#endif // __SIMPLE_LOG_H__