00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00035 #include "OW_config.h"
00036 #include "OW_FileAppender.hpp"
00037 #include "OW_Format.hpp"
00038 #include "OW_Logger.hpp"
00039 #include "OW_LogMessage.hpp"
00040 #include "OW_Mutex.hpp"
00041 #include "OW_MutexLock.hpp"
00042 #include "OW_FileSystem.hpp"
00043
00044 #include <fstream>
00045
00046 namespace OW_NAMESPACE
00047 {
00048
00050 FileAppender::FileAppender(const StringArray& components,
00051 const StringArray& categories,
00052 const char* filename,
00053 const String& pattern,
00054 UInt64 maxFileSize,
00055 unsigned int maxBackupIndex,
00056 bool flushLog)
00057 : LogAppender(components, categories, pattern)
00058 , m_filename(filename)
00059 , m_maxFileSize(maxFileSize)
00060 , m_maxBackupIndex(maxBackupIndex)
00061 , m_flushLog(flushLog)
00062 {
00063 m_log.open(m_filename.c_str(), std::ios::out | std::ios::app);
00064 if (!m_log)
00065 {
00066 OW_THROW(LoggerException, Format("FileAppender: Unable to open file: %1", m_filename).toString().c_str() );
00067 }
00068 }
00069
00071 FileAppender::~FileAppender()
00072 {
00073 }
00074
00076 namespace
00077 {
00078 Mutex fileGuard;
00079 }
00080 void
00081 FileAppender::doProcessLogMessage(const String& formattedMessage, const LogMessage& message) const
00082 {
00083 MutexLock lock(fileGuard);
00084
00085
00086 if (!FileSystem::exists(m_filename.c_str()))
00087 {
00088 m_log.close();
00089 m_log.open(m_filename.c_str(), std::ios::out | std::ios::app);
00090 }
00091
00092 if (!m_log)
00093 {
00094
00095 return;
00096 }
00097
00098 m_log.write(formattedMessage.c_str(), formattedMessage.length());
00099 m_log << '\n';
00100
00101 if (m_flushLog)
00102 {
00103 m_log.flush();
00104 }
00105
00106
00107 if (m_maxFileSize != NO_MAX_LOG_SIZE && m_log.tellp() >= static_cast<std::streampos>(m_maxFileSize * 1024))
00108 {
00109
00110
00111
00112 m_log.close();
00113
00114 if (m_maxBackupIndex > 0)
00115 {
00116
00117 FileSystem::removeFile(m_filename + '.' + String(m_maxBackupIndex));
00118
00119
00120 for (unsigned int i = m_maxBackupIndex - 1; i >= 1; --i)
00121 {
00122 FileSystem::renameFile(m_filename + '.' + String(i), m_filename + '.' + String(i + 1));
00123 }
00124
00125 if (!FileSystem::renameFile(m_filename, m_filename + ".1"))
00126 {
00127
00128 return;
00129 }
00130 }
00131
00132
00133 m_log.open(m_filename.c_str(), std::ios_base::out | std::ios_base::trunc);
00134 }
00135 }
00136
00138 const String FileAppender::STR_DEFAULT_MESSAGE_PATTERN("%d{%a %b %d %H:%M:%S %Y} [%t]: %m");
00139
00140 }
00141
00142
00143
00144