Vidalia
0.2.15
|
00001 /* 00002 ** This file is part of Vidalia, and is subject to the license terms in the 00003 ** LICENSE file, found in the top level directory of this distribution. If you 00004 ** did not receive the LICENSE file with this file, you may obtain it from the 00005 ** Vidalia source package distributed by the Vidalia Project at 00006 ** http://www.torproject.org/projects/vidalia.html. No part of Vidalia, 00007 ** including this file, may be copied, modified, propagated, or distributed 00008 ** except according to the terms described in the LICENSE file. 00009 */ 00010 00011 /* 00012 ** \file LogFile.cpp 00013 ** \brief Logs messages from Tor to a file 00014 */ 00015 00016 #include "LogFile.h" 00017 00018 #include "stringutil.h" 00019 00020 #include <QDir> 00021 00022 00023 /** Default constructor. */ 00024 LogFile::LogFile() 00025 { 00026 _file = 0; 00027 } 00028 00029 /** Destructor. */ 00030 LogFile::~LogFile() 00031 { 00032 if (_file) { 00033 delete _file; 00034 } 00035 } 00036 00037 /** Creates a path to the given log file. */ 00038 bool 00039 LogFile::createPathToFile(QString filename) 00040 { 00041 QDir dir = QFileInfo(filename).absoluteDir(); 00042 if (!dir.exists()) { 00043 return dir.mkpath(dir.absolutePath()); 00044 } 00045 return true; 00046 } 00047 00048 /** Opens a log file for writing. */ 00049 bool 00050 LogFile::open(QString filename, QString *errmsg) 00051 { 00052 QFile *newLogFile; 00053 00054 /* If the file is already open, then no need to open it again */ 00055 if (_file && _file->isOpen()) { 00056 if (_file->fileName() == filename) { 00057 return true; 00058 } 00059 } 00060 00061 /* Create the path to the log file, if necessary */ 00062 if (!createPathToFile(filename)) { 00063 return err(errmsg, "Unable to create path to log file."); 00064 } 00065 00066 /* Try to open the new log file */ 00067 newLogFile = new QFile(filename); 00068 if (!newLogFile->open(QFile::WriteOnly|QIODevice::Append|QIODevice::Text)) { 00069 delete newLogFile; 00070 return err(errmsg, newLogFile->errorString()); 00071 } 00072 00073 /* Rotate the new log file in place of the old one */ 00074 if (_file) { 00075 delete _file; 00076 } 00077 _file = newLogFile; 00078 _stream.setDevice(_file); 00079 return true; 00080 } 00081 00082 /** Closes an open log file. */ 00083 void 00084 LogFile::close() 00085 { 00086 if (_file) { 00087 delete _file; 00088 _file = 0; 00089 } 00090 } 00091 00092 /** Returns true if the logfile is currently open. */ 00093 bool 00094 LogFile::isOpen() 00095 { 00096 return (_file && _file->isOpen()); 00097 } 00098 00099 /** Returns the filename of the current log file. */ 00100 QString 00101 LogFile::filename() 00102 { 00103 return (_file ? _file->fileName() : QString());; 00104 } 00105 00106 /** Overloaded ostream operator. */ 00107 LogFile& 00108 LogFile::operator<<(const QString &s) 00109 { 00110 if (_file) { 00111 _stream << s; 00112 _stream.flush(); 00113 } 00114 return *this; 00115 } 00116