파일 로깅

프로그래밍/C++ 2015. 9. 10. 17:07 |

테스트 할 때 로그를 출력하기 거시기 할 때 그냥 파일에 쓰게 간단히 코드를 만들어 둠.

 

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
#ifndef _BABO_LOG_H
#define _BABO_LOG_H
 
#include <cstdio>
#include <cstdarg>
#include <fstream>
 
using namespace std;
 
class Log {
private:
    Log() { file.open("/var/log/log.txt", ios::out | ios::app); } // 파일에 계속 이어 붙인다.
    ~Log() { file.close(); }
    ofstream file;
public:
    static Log &instance() { // singleton
        static Log _instance;
        return _instance;
    }
    void log(const char *format, ...) {
        char buffer[256];
        va_list args;
        va_start(args, format);
        vsnprintf(buffer, sizeof(buffer), format, args);
        va_end(args);
        file << buffer;
    }
};
 
#define log(format, args...) Log::instance().log(format, ##args)
 
#endif // _BABO_LOG_H

 

 

다음과 같이 사용하면 된다.

1
2
3
4
5
6
7
#include "Log.h"
 
int main() {
    for (int i = 0; i < 10; i++)
        log("%d\n", i);
    return 0;
}


: