houxiao
2017-02-13 0688756b71b40e0ac60c68af2fa1fe4aaeb1718d
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
 * logger.cc
 *
 *
 * Logger Library
 *
 *
 * Copyright (C) 2013-2017  Bryant Moscon - bmoscon@gmail.com
 * 
 * Please see the LICENSE file for the terms and conditions 
 * associated with this software.
 *
 */
 
#include "logger.hpp"
 
Logger::Logger(std::ostream& s) : _file(), 
                _log(s),
                _level(INFO),
                _line_level(VERBOSE),
                _default_line_level(VERBOSE)
{
}
 
 
Logger::Logger(const char *f) : _file(f, std::ios::out | std::ios::app), 
                _log(_file),
                _level(INFO),
                _line_level(VERBOSE),
                _default_line_level(VERBOSE)
{
    assert(_file.is_open());
}
 
 
Logger::Logger(const std::string& f) : _file(f.c_str(), std::ios::out | std::ios::app), 
                       _log(_file),
                       _level(INFO),
                       _line_level(VERBOSE),
                       _default_line_level(VERBOSE)
{
    assert(_file.is_open());
}
 
 
Logger::~Logger()
{
    if (_file.is_open()) {
    _log.flush();
    _file.close();
    }
    else {
        _log.flush();
    }
}
 
 
void Logger::set_level(const logger_level& level)
{
    _level = level;
}  
 
 
void Logger::set_default_line_level(const logger_level& level)
{
    _default_line_level = level;
}
 
 
void Logger::flush()
{
    if (_line_level >= _level) {
        _log << get_time() << " -- [" << level_str(_line_level) << "] -- " << str();
        if (_file.is_open())
            _log.flush();
    }
    
    str("");
    _line_level = _default_line_level;
}
 
 
Logger& Logger::operator<<(const logger_level& level)
{
    _line_level = level;
    return (*this);
}
 
 
Logger& Logger::operator<<(LoggerManip m)
    return m(*this);
}
 
 
std::string Logger::get_time() const
{
    struct tm *timeinfo;
    time_t rawtime;
    char *time_buf;
    
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    time_buf = asctime(timeinfo);
    
    std::string ret(time_buf);
    if (!ret.empty() && ret[ret.length() - 1] == '\n') {
    ret.erase(ret.length()-1);
    }
    
    return (ret);
}
 
 
inline const char* Logger::level_str(const logger_level& level)
{
    switch (level) {
    case VERBOSE:
    return ("VRB");
    case DEBUG:
    return ("DBG");
    case INFO:
    return ("INF");
    case WARNING:
    return ("WRN");
    case ERROR:
    return ("ERR");
    case CRITICAL:
    return ("CRT");
    default:
    assert(false);
    }
}