// Log. h # ifndef log_h # define log_h # include <fstream> # include <string> # include <sstream> # include <ctime> using namespace STD; /*** class used to output log files. */class log {public: log ();~ Log (); bool open (string strfilename); void close (); bool commonloginit (); // open the default Log File void enable (); void disable (); string gettimestr (); Template <typename T> void logout (const T & Value) {If (m_benabled) {m_tologfile <value ;}} template <typename T> void logoutln (const T & Value) {If (m_benabled) {m_tologfile <value <Endl ;}} void logoutln () {If (m_benabled) {m_tologfile <Endl ;}} Template <typename T> log & operator <(const T & Value) {If (m_benabled) {m_tologfile <value ;}return (* This );} log & operator <(ostream & (* _ PFn) (ostream &) {If (m_benabled) {(* _ PFn) (m_tologfile );} return (* This);} private: Template <typename T> string valuetostr (T value) {ostringstream ost; Ost <value; return OST. STR () ;}private: ofstream m_tologfile; bool m_benabled ;};# endif // ======== ======================/// Log. CPP # include "log. H "log: log (): m_benabled (true) {} log ::~ Log () {} bool log: open (string sfilename) {m_tologfile.open (sfilename. c_str (), ios_base: Out | ios_base: APP); If (! M_tologfile) {return false;} return true;} void log: Close () {If (m_tologfile.is_open () {m_tologfile.close () ;}} bool log: commonloginit () {time_t tnowtime; time (& tnowtime); TM * tlocaltime = localtime (& tnowtime); // obtain the date string sdatestr = valuetostr (tlocaltime-> tm_year + 1900) + "-" + valuetostr (tlocaltime-> tm_mon + 1) + "-" + valuetostr (tlocaltime-> tm_mday); Return open ("log _" + sdatestr + ". log ");} void log: Enable () {m_benabled = true;} void log: Disable () {m_benabled = false ;} // obtain the string log of the current time: gettimestr () {time_t tnowtime; time (& tnowtime); TM * tlocaltime = localtime (& tnowtime ); // "2011-07-18 23:03:01"; string strformat = "% Y-% m-% d % H: % m: % s "; char strdatetime [30] = {'\ 0'}; strftime (strdatetime, 30, strformat. c_str (), tlocaltime); string strres = strdatetime; return strres;} // This log class is used to output simple log text files. // test: Main. CPP # include "log. H "int main () {log mainlog; mainlog. commonloginit (); mainlog <mainlog. gettimestr () <"test log class. "<Endl ;}