Vidalia 0.3.1
LogFile.cpp
Go to the documentation of this file.
1/*
2** This file is part of Vidalia, and is subject to the license terms in the
3** LICENSE file, found in the top level directory of this distribution. If you
4** did not receive the LICENSE file with this file, you may obtain it from the
5** Vidalia source package distributed by the Vidalia Project at
6** http://www.torproject.org/projects/vidalia.html. No part of Vidalia,
7** including this file, may be copied, modified, propagated, or distributed
8** except according to the terms described in the LICENSE file.
9*/
10
11/*
12** \file LogFile.cpp
13** \brief Logs messages from Tor to a file
14*/
15
16#include "LogFile.h"
17
18#include "stringutil.h"
19
20#include <QDir>
21
22
23/** Default constructor. */
25{
26 _file = 0;
27}
28
29/** Destructor. */
31{
32 if (_file) {
33 delete _file;
34 }
35}
36
37/** Creates a path to the given log file. */
38bool
40{
41 QDir dir = QFileInfo(filename).absoluteDir();
42 if (!dir.exists()) {
43 return dir.mkpath(dir.absolutePath());
44 }
45 return true;
46}
47
48/** Opens a log file for writing. */
49bool
50LogFile::open(QString filename, QString *errmsg)
51{
52 QFile *newLogFile;
53
54 /* If the file is already open, then no need to open it again */
55 if (_file && _file->isOpen()) {
56 if (_file->fileName() == filename) {
57 return true;
58 }
59 }
60
61 /* Create the path to the log file, if necessary */
63 return err(errmsg, "Unable to create path to log file.");
64 }
65
66 /* Try to open the new log file */
67 newLogFile = new QFile(filename);
68 if (!newLogFile->open(QFile::WriteOnly|QIODevice::Append|QIODevice::Text)) {
69 delete newLogFile;
70 return err(errmsg, newLogFile->errorString());
71 }
72
73 /* Rotate the new log file in place of the old one */
74 if (_file) {
75 delete _file;
76 }
77 _file = newLogFile;
78 _stream.setDevice(_file);
79 return true;
80}
81
82/** Closes an open log file. */
83void
85{
86 if (_file) {
87 delete _file;
88 _file = 0;
89 }
90}
91
92/** Returns true if the logfile is currently open. */
93bool
95{
96 return (_file && _file->isOpen());
97}
98
99/** Returns the filename of the current log file. */
100QString
102{
103 return (_file ? _file->fileName() : QString());;
104}
105
106/** Overloaded ostream operator. */
108LogFile::operator<<(const QString &s)
109{
110 if (_file) {
111 _stream << s;
112 _stream.flush();
113 }
114 return *this;
115}
116
QString filename()
Definition: LogFile.cpp:101
bool open(QString filename, QString *errmsg=0)
Definition: LogFile.cpp:50
QFile * _file
Definition: LogFile.h:52
~LogFile()
Definition: LogFile.cpp:30
void close()
Definition: LogFile.cpp:84
QTextStream _stream
Definition: LogFile.h:53
bool createPathToFile(QString filename)
Definition: LogFile.cpp:39
LogFile & operator<<(const QString &s)
Definition: LogFile.cpp:108
bool isOpen()
Definition: LogFile.cpp:94
LogFile()
Definition: LogFile.cpp:24
bool err(QString *str, const QString &errmsg)
Definition: stringutil.cpp:37