1 //=============================================================================
2 //
3 // Adventure Game Studio (AGS)
4 //
5 // Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
6 // The full list of copyright holders can be found in the Copyright.txt
7 // file, which is part of this source code distribution.
8 //
9 // The AGS source code is provided under the Artistic License 2.0.
10 // A copy of this license can be found in the file License.txt and at
11 // http://www.opensource.org/licenses/artistic-license-2.0.php
12 //
13 //=============================================================================
14
15 #include <string.h>
16 #include "debug/logfile.h"
17 #include "util/file.h"
18 #include "util/stream.h"
19
20 namespace AGS
21 {
22 namespace Engine
23 {
24
25 using namespace Common;
26
LogFile()27 LogFile::LogFile()
28 : _openMode(kLogFile_OpenOverwrite)
29 {
30 }
31
PrintMessage(const DebugMessage & msg)32 void LogFile::PrintMessage(const DebugMessage &msg)
33 {
34 if (!_file.get())
35 {
36 if (_filePath.IsEmpty())
37 return;
38 // Delayed file open
39 String fp = _filePath; // the file gets reset before reopening, so we need to save filepath in a local var
40 if (!OpenFile(fp, _openMode))
41 {
42 Debug::Printf("Unable to write log to '%s'.", _filePath.GetCStr());
43 _filePath = "";
44 return;
45 }
46 }
47
48 if (!msg.GroupName.IsEmpty())
49 {
50 _file->Write(msg.GroupName, msg.GroupName.GetLength());
51 _file->Write(" : ", 3);
52 }
53 _file->Write(msg.Text, msg.Text.GetLength());
54 _file->WriteInt8('\n');
55 // We should flush after every write to the log; this will make writing
56 // bit slower, but will increase the chances that all latest output
57 // will get to the disk in case of program crash.
58 _file->Flush();
59 }
60
OpenFile(const String & file_path,LogFileOpenMode open_mode,bool open_at_first_msg)61 bool LogFile::OpenFile(const String &file_path, LogFileOpenMode open_mode, bool open_at_first_msg)
62 {
63 CloseFile();
64
65 _filePath = file_path;
66 _openMode = open_mode;
67 if (!open_at_first_msg)
68 {
69 _file.reset(File::OpenFile(file_path,
70 open_mode == kLogFile_OpenAppend ? Common::kFile_Create : Common::kFile_CreateAlways,
71 Common::kFile_Write));
72 }
73 return _file.get() != NULL || open_at_first_msg;
74 }
75
CloseFile()76 void LogFile::CloseFile()
77 {
78 _file.reset();
79 _filePath.Empty();
80 }
81
82 } // namespace Engine
83 } // namespace AGS
84