Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/libraries/util/OutputHandler.cc @ 6247

Last change on this file since 6247 was 6105, checked in by rgrieder, 15 years ago

Merged console branch back to trunk.

  • Property svn:eol-style set to native
File size: 9.6 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Fabian 'x3n' Landau
24 *   Co-authors:
25 *      Reto Grieder
26 *
27 */
28
29/**
30@file
31@brief
32    Definition of classes related to output (logging).
33*/
34
35#include "OutputHandler.h"
36
37#include <algorithm>
38#include <ctime>
39#include <cstdlib>
40#include <fstream>
41#include <sstream>
42
43#include "Debug.h"
44
45namespace orxonox
46{
47    //! How the log file shall be named on the filesystem
48    const std::string logFileBaseName_g = "orxonox.log";
49
50    /////////////////////////
51    ///// LogFileWriter /////
52    /////////////////////////
53    /**
54    @brief
55        Writes the output to the log file.
56    @note
57        As long as the correct log path is not yet known (for pre main code), the
58        LogFileWriter will write to a temporary file in /temp (Unix) or %TEMP% (Windows).
59        As soon as you set the correct path setLogPath the content of the temporary file
60        is read and put into the new file as well.
61    */
62    class LogFileWriter : public OutputListener
63    {
64    public:
65        /**
66        @brief
67            Gets temporary log path and starts the log file
68        @param outputHandler
69            This is only required to avoid another call to getInstance (this c'tor was
70            called from getInstance!)
71        */
72        LogFileWriter()
73            : OutputListener(OutputHandler::logFileOutputListenerName_s)
74        {
75            // Get path for a temporary file
76#ifdef ORXONOX_PLATFORM_WINDOWS
77            char* pTempDir = getenv("TEMP");
78            this->logFilename_ = std::string(pTempDir) + "/" + logFileBaseName_g;
79#else
80            this->logFilename_ = std::string("/tmp/") + logFileBaseName_g;
81#endif
82
83            // Get current time
84            time_t rawtime;
85            struct tm* timeinfo;
86            time(&rawtime);
87            timeinfo = localtime(&rawtime);
88
89            this->logFile_.open(this->logFilename_.c_str(), std::fstream::out);
90            this->logFile_ << "Started log on " << asctime(timeinfo) << std::endl;
91            this->logFile_.flush();
92
93            this->outputStream_ = &this->logFile_;
94        }
95
96        //! Closes the log file
97        ~LogFileWriter()
98        {
99            this->logFile_ << "Closed log" << std::endl;
100            this->logFile_.close();
101        }
102
103        //! Changes the log path
104        void setLogPath(const std::string& path)
105        {
106            this->logFile_.close();
107            // Read old file into a buffer
108            std::ifstream old(this->logFilename_.c_str());
109            this->logFilename_ = path + logFileBaseName_g;
110            // Open the new file and feed it the content of the old one
111            this->logFile_.open(this->logFilename_.c_str(), std::fstream::out);
112            this->logFile_ << old.rdbuf();
113            this->logFile_.flush();
114            old.close();
115        }
116
117    private:
118        std::ofstream logFile_;     //! File handle for the log file
119        std::string   logFilename_; //! Filename of the log file
120    };
121
122
123    /////////////////////////
124    ///// ConsoleWriter /////
125    /////////////////////////
126    /**
127    @brief
128        Writes the output to std::cout.
129    @note
130        This listener will usually be disable once an actual shell with console is instantiated.
131    */
132    class ConsoleWriter : public OutputListener
133    {
134    public:
135        //! Only assigns the output stream with std::cout
136        ConsoleWriter()
137            : OutputListener("consoleLog")
138        {
139            this->outputStream_ = &std::cout;
140        }
141    };
142
143
144    ///////////////////////////
145    ///// MemoryLogWriter /////
146    ///////////////////////////
147    /**
148    @brief
149        OutputListener that writes all the output piece by piece to an array
150        associated with the corresponding output level.
151    @note
152        Only output below or equal to the current soft debug level is written
153        to minimise huge arrays for the normal run.
154    */
155    class MemoryLogWriter : public OutputListener
156    {
157    public:
158        friend class OutputHandler;
159
160        /**
161        @brief
162            Sets the right soft debug level and registers itself
163        @param outputHandler
164            This is only required to avoid another call to getInstance (this c'tor was
165            called from getInstance!)
166        */
167        MemoryLogWriter()
168            : OutputListener("memoryLog")
169        {
170            this->outputStream_ = &this->buffer_;
171        }
172
173        //! Pushed the just written output to the internal array
174        void outputChanged(int level)
175        {
176            // Read ostringstream and store it
177            this->output_.push_back(std::make_pair(level, this->buffer_.str()));
178            // Clear content and flags
179            this->buffer_.str(std::string());
180            this->buffer_.clear();
181        }
182
183    private:
184        std::ostringstream                        buffer_; //! Stream object used to process the output
185        std::vector<std::pair<int, std::string> > output_; //! Vector containing ALL output
186    };
187
188
189    /////////////////////////
190    ///// OutputHandler /////
191    /////////////////////////
192    const std::string OutputHandler::logFileOutputListenerName_s = "logFile";
193          int         OutputHandler::softDebugLevel_s = hardDebugLevel;
194
195    //! Creates the LogFileWriter and the MemoryLogWriter
196    OutputHandler::OutputHandler()
197        : outputLevel_(OutputLevel::Verbose)
198    {
199#ifdef ORXONOX_RELEASE
200        const OutputLevel::Value defaultLevelConsole = OutputLevel::Error;
201        const OutputLevel::Value defaultLevelLogFile = OutputLevel::Info;
202#else
203        const OutputLevel::Value defaultLevelConsole = OutputLevel::Info;
204        const OutputLevel::Value defaultLevelLogFile = OutputLevel::Debug;
205#endif
206
207        this->logFile_ = new LogFileWriter();
208        // Use default level until we get the configValue from the Core
209        this->logFile_->softDebugLevel_ = defaultLevelLogFile;
210        this->registerOutputListener(this->logFile_);
211
212        this->consoleWriter_ = new ConsoleWriter();
213        this->consoleWriter_->softDebugLevel_ = defaultLevelConsole;
214        this->registerOutputListener(this->consoleWriter_);
215
216        this->output_  = new MemoryLogWriter();
217        // We capture as much input as the listener with the highest level
218        this->output_->softDebugLevel_ = getSoftDebugLevel();
219        this->registerOutputListener(this->output_);
220    }
221
222    //! Destroys the LogFileWriter and the MemoryLogWriter
223    OutputHandler::~OutputHandler()
224    {
225        delete this->logFile_;
226        delete this->output_;
227    }
228
229    OutputHandler& OutputHandler::getInstance()
230    {
231        static OutputHandler orxout;
232        return orxout;
233    }
234
235    void OutputHandler::registerOutputListener(OutputListener* listener)
236    {
237        for (std::list<OutputListener*>::const_iterator it = this->listeners_.begin(); it != this->listeners_.end(); ++it)
238        {
239            if ((*it)->name_ == listener->name_)
240            {
241                COUT(2) << "OutputHandler, Warning: Trying to register two listeners with the same name!" << std::endl;
242                return;
243            }
244        }
245        this->listeners_.push_back(listener);
246        // Update global soft debug level
247        this->setSoftDebugLevel(listener->getOutputListenerName(), listener->getSoftDebugLevel());
248    }
249
250    void OutputHandler::unregisterOutputListener(OutputListener* listener)
251    {
252        this->listeners_.remove(listener);
253    }
254
255    void OutputHandler::setLogPath(const std::string& path)
256    {
257        this->logFile_->setLogPath(path);
258    }
259
260    void OutputHandler::disableCout()
261    {
262        this->unregisterOutputListener(this->consoleWriter_);
263    }
264
265    void OutputHandler::enableCout()
266    {
267        this->registerOutputListener(this->consoleWriter_);
268    }
269
270    OutputHandler::OutputVectorIterator OutputHandler::getOutputVectorBegin() const
271    {
272        return this->output_->output_.begin();
273    }
274
275    OutputHandler::OutputVectorIterator OutputHandler::getOutputVectorEnd() const
276    {
277        return this->output_->output_.end();
278    }
279
280    int OutputHandler::getSoftDebugLevel(const std::string& name) const
281    {
282        for (std::list<OutputListener*>::const_iterator it = this->listeners_.begin(); it != this->listeners_.end(); ++it)
283        {
284            if ((*it)->name_ == name)
285                return (*it)->softDebugLevel_;
286        }
287        return -1;
288    }
289
290    void OutputHandler::setSoftDebugLevel(const std::string& name, int level)
291    {
292        int globalSoftDebugLevel = -1;
293        for (std::list<OutputListener*>::const_iterator it = this->listeners_.begin(); it != this->listeners_.end(); ++it)
294        {
295            if ((*it)->name_ == name)
296                (*it)->softDebugLevel_ = level;
297            if ((*it)->softDebugLevel_ > globalSoftDebugLevel)
298                globalSoftDebugLevel = (*it)->softDebugLevel_;
299        }
300        // Update global soft debug level
301        OutputHandler::softDebugLevel_s = globalSoftDebugLevel;
302    }
303}
Note: See TracBrowser for help on using the repository browser.