Skip to content

Instantly share code, notes, and snippets.

@jzgriffin
Created December 8, 2012 20:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jzgriffin/4241898 to your computer and use it in GitHub Desktop.
Save jzgriffin/4241898 to your computer and use it in GitHub Desktop.
C++ Logging Class
#include "Format.hpp"
#include <iomanip>
std::ostream& operator<<(std::ostream& out, std::tm* dt)
{
return out // ISO 8601 without timezone
<< std::setfill('0') << std::setw(4) << dt->tm_year + 1900 << "-"
<< std::setfill('0') << std::setw(2) << dt->tm_mday << "-"
<< std::setfill('0') << std::setw(2) << dt->tm_mon + 1 << " "
<< std::setfill('0') << std::setw(2) << dt->tm_hour << ":"
<< std::setfill('0') << std::setw(2) << dt->tm_min << ":"
<< std::setfill('0') << std::setw(2) << dt->tm_sec;
}
#pragma once
#include <ctime>
#include <ostream>
std::ostream& operator<<(std::ostream& out, std::tm* dt);
#include "Format.hpp"
#include "Log.hpp"
#include <ctime>
#include <iostream>
int Log::Buffer::sync()
{
auto ts = std::time(0);
_log._out << "[" << std::localtime(&ts) << "] " << str();
if (_log._console) std::cout << str();
str("");
return 0;
}
bool Log::open(std::string const& file)
{
_file = file;
_out.open(file.c_str());
return _out.is_open();
}
#pragma once
#include <fstream>
#include <ostream>
#include <sstream>
#include <string>
// Log: A std::ofstream that prefixes every message (text between flushes) with
// the current time. Note, you must use std::endl for terminating lines in order
// for the time stamp to be written before each line.
//
// Messages can optionally be output to stdout as well.
class Log : NonCopyable, public std::ostream {
public:
Log()
: std::ostream(&_buffer)
, _buffer(*this)
, _console(false)
{}
Log(std::string const& file, bool console = false)
: std::ostream(&_buffer)
, _buffer(*this)
, _file(file)
, _out(file.c_str())
, _console(console)
{}
bool open(std::string const& file);
void close() { _out.close(); }
bool isOpen() const { return _out.is_open(); }
std::string const& file() const { return _file; }
bool console() const { return _console; }
void console(bool c) { _console = c; }
private:
// Buffer: A std::stringbuf that outputs the time stamp and message to a
// Log's _out upon being synced.
class Buffer : public std::stringbuf {
public:
Buffer(Log& log)
: _log(log)
{}
int sync();
private:
Log& _log;
};
friend class Buffer;
Buffer _buffer;
std::string _file;
std::ofstream _out;
bool _console;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment