User Tools

Site Tools


Minimal sync file logger

logger.cpp
/*
 * logger.cpp
 *
 * Copyright 2015 Oleg Borodin  <borodin@unix7.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 */
 
#include <iostream>
#include <istream>
#include <ostream>
#include <fstream>
#include <sstream>
 
#include <string>
#include <ctime>
 
 
class logger {
    private:
        std::string path = "/dev/null";
 
        std::string timestamp() {
            time_t now = time(0);
            tm *timedate = gmtime(&now);
            std::stringstream timestamp_stream;
            timestamp_stream
                << 1900 + timedate->tm_year
                << "-" << std::setw(2) << std::setfill('0') << 1 + timedate->tm_mon
                << "-" << std::setw(2) << std::setfill('0') << timedate->tm_mday;
            timestamp_stream
                << " " << std::setw(2) << std::setfill('0') << timedate->tm_hour
                << ":" << std::setw(2) << std::setfill('0') << timedate->tm_min
                << ":" << std::setw(2) << std::setfill('0') << timedate->tm_sec
                << " UTC";
            return timestamp_stream.str();
        }
 
    public:
        logger(std::string _path) : path(_path) {
        }
        void write(std::string str) {
            std::ofstream log_stream(path, std::ofstream::app);
            log_stream << timestamp() << " " << str << std::endl;
            log_stream.flush();
            log_stream.close();
        }
};
 
int main() {
 
    logger log("some.log");
    log.write("hello");
    log.write("people");
 
}

Out

$ cat some.log
2015-07-05 09:18:59 UTC hello
2015-07-05 09:18:59 UTC people

First PagePrevious PageBack to overviewNext PageLast Page