fileappender.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. // -*- C++ -*-
  2. // Module: Log4CPLUS
  3. // File: fileappender.h
  4. // Created: 6/2001
  5. // Author: Tad E. Smith
  6. //
  7. //
  8. // Copyright 2001-2015 Tad E. Smith
  9. //
  10. // Licensed under the Apache License, Version 2.0 (the "License");
  11. // you may not use this file except in compliance with the License.
  12. // You may obtain a copy of the License at
  13. //
  14. // http://www.apache.org/licenses/LICENSE-2.0
  15. //
  16. // Unless required by applicable law or agreed to in writing, software
  17. // distributed under the License is distributed on an "AS IS" BASIS,
  18. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. // See the License for the specific language governing permissions and
  20. // limitations under the License.
  21. /** @file */
  22. #ifndef LOG4CPLUS_FILE_APPENDER_HEADER_
  23. #define LOG4CPLUS_FILE_APPENDER_HEADER_
  24. #include <log4cplus/config.hxx>
  25. #if defined (LOG4CPLUS_HAVE_PRAGMA_ONCE)
  26. #pragma once
  27. #endif
  28. #include <log4cplus/appender.h>
  29. #include <log4cplus/fstreams.h>
  30. #include <log4cplus/helpers/timehelper.h>
  31. #include <log4cplus/helpers/lockfile.h>
  32. #include <fstream>
  33. #include <locale>
  34. #include <memory>
  35. namespace log4cplus
  36. {
  37. /**
  38. * Base class for Appenders writing log events to a file.
  39. * It is constructed with uninitialized file object, so all
  40. * classes derived from FileAppenderBase _must_ call init() method.
  41. *
  42. * <h3>Properties</h3>
  43. * <dl>
  44. * <dt><tt>File</tt></dt>
  45. * <dd>This property specifies output file name.</dd>
  46. *
  47. * <dt><tt>ImmediateFlush</tt></dt>
  48. * <dd>When it is set true, output stream will be flushed after
  49. * each appended event.</dd>
  50. *
  51. * <dt><tt>Append</tt></dt>
  52. * <dd>When it is set true, output file will be appended to
  53. * instead of being truncated at opening.</dd>
  54. *
  55. * <dt><tt>ReopenDelay</tt></dt>
  56. * <dd>This property sets a delay after which the appender will try
  57. * to reopen log file again, after last logging failure.
  58. * </dd>
  59. *
  60. * <dt><tt>BufferSize</tt></dt>
  61. * <dd>Non-zero value of this property sets up buffering of output
  62. * stream using a buffer of given size.
  63. * </dd>
  64. *
  65. * <dt><tt>UseLockFile</tt></dt>
  66. * <dd>Set this property to <tt>true</tt> if you want your output
  67. * to go into a log file shared by multiple processes. When this
  68. * property is set to true then log4cplus uses OS specific
  69. * facilities (e.g., <code>lockf()</code>) to provide
  70. * inter-process file locking.
  71. * \sa Appender
  72. * </dd>
  73. *
  74. * <dt><tt>LockFile</tt></dt>
  75. * <dd>This property specifies lock file, file used for
  76. * inter-process synchronization of log file access. When this
  77. * property is not specified, the value is derived from
  78. * <tt>File</tt> property by addition of ".lock" suffix. The
  79. * property is only used when <tt>UseLockFile</tt> is set to true.
  80. * \sa Appender
  81. * </dd>
  82. *
  83. * <dt><tt>Locale</tt></dt>
  84. * <dd>This property specifies a locale name that will be imbued
  85. * into output stream. Locale can be specified either by system
  86. * specific locale name, e.g., <tt>en_US.UTF-8</tt>, or by one of
  87. * four recognized keywords: <tt>GLOBAL</tt>, <tt>DEFAULT</tt>
  88. * (which is an alias for <tt>GLOBAL</tt>), <tt>USER</tt> and
  89. * <tt>CLASSIC</tt>. When specified locale is not available,
  90. * <tt>GLOBAL</tt> is used instead. It is possible to register
  91. * additional locale keywords by registering an instance of
  92. * <code>spi::LocaleFactory</code> in
  93. * <code>spi::LocaleFactoryRegistry</code>.
  94. * \sa spi::getLocaleFactoryRegistry()
  95. * </dd>
  96. *
  97. * <dt><tt>CreateDirs</tt></dt>
  98. * <dd>Set this property to <tt>true</tt> if you want to create
  99. * missing directories in path leading to log file and lock file.
  100. * </dd>
  101. * </dl>
  102. */
  103. class LOG4CPLUS_EXPORT FileAppenderBase : public Appender {
  104. public:
  105. // Methods
  106. virtual void close();
  107. //! Redefine default locale for output stream. It may be a good idea to
  108. //! provide UTF-8 locale in case UNICODE macro is defined.
  109. virtual std::locale imbue(std::locale const& loc);
  110. //! \returns Locale imbued in fstream.
  111. virtual std::locale getloc () const;
  112. protected:
  113. // Ctors
  114. FileAppenderBase(const log4cplus::tstring& filename,
  115. std::ios_base::openmode mode = std::ios_base::trunc,
  116. bool immediateFlush = true,
  117. bool createDirs = false);
  118. FileAppenderBase(const log4cplus::helpers::Properties& properties,
  119. std::ios_base::openmode mode = std::ios_base::trunc);
  120. void init();
  121. virtual void append(const spi::InternalLoggingEvent& event);
  122. virtual void open(std::ios_base::openmode mode);
  123. bool reopen();
  124. // Data
  125. /**
  126. * Immediate flush means that the underlying writer or output stream
  127. * will be flushed at the end of each append operation. Immediate
  128. * flush is slower but ensures that each append request is actually
  129. * written. If <code>immediateFlush</code> is set to
  130. * <code>false</code>, then there is a good chance that the last few
  131. * logs events are not actually written to persistent media if and
  132. * when the application crashes.
  133. *
  134. * The <code>immediateFlush</code> variable is set to
  135. * <code>true</code> by default.
  136. */
  137. bool immediateFlush;
  138. /**
  139. * When this variable is true, FileAppender will try to create
  140. * missing directories in path leading to log file.
  141. *
  142. * The `createDirs` variable is set to `false` by default.
  143. */
  144. bool createDirs;
  145. /**
  146. * When any append operation fails, <code>reopenDelay</code> says
  147. * for how many seconds the next attempt to re-open the log file and
  148. * resume logging will be delayed. If <code>reopenDelay</code> is zero,
  149. * each failed append operation will cause log file to be re-opened.
  150. * By default, <code>reopenDelay</code> is 1 second.
  151. */
  152. int reopenDelay;
  153. unsigned long bufferSize;
  154. log4cplus::tchar * buffer;
  155. log4cplus::tofstream out;
  156. log4cplus::tstring filename;
  157. log4cplus::tstring localeName;
  158. log4cplus::tstring lockFileName;
  159. std::ios_base::openmode fileOpenMode;
  160. log4cplus::helpers::Time reopen_time;
  161. private:
  162. // Disallow copying of instances of this class
  163. FileAppenderBase(const FileAppenderBase&);
  164. FileAppenderBase& operator=(const FileAppenderBase&);
  165. };
  166. /**
  167. * Appends log events to a file.
  168. *
  169. * <h3>Properties</h3>
  170. * <p>It has no properties additional to {@link FileAppenderBase}.
  171. */
  172. class LOG4CPLUS_EXPORT FileAppender : public FileAppenderBase {
  173. public:
  174. // Ctors
  175. FileAppender(const log4cplus::tstring& filename,
  176. std::ios_base::openmode mode = std::ios_base::trunc,
  177. bool immediateFlush = true,
  178. bool createDirs = false);
  179. FileAppender(const log4cplus::helpers::Properties& properties,
  180. std::ios_base::openmode mode = std::ios_base::trunc);
  181. // Dtor
  182. virtual ~FileAppender();
  183. protected:
  184. void init();
  185. };
  186. typedef helpers::SharedObjectPtr<FileAppender> SharedFileAppenderPtr;
  187. /**
  188. * RollingFileAppender extends FileAppender to backup the log
  189. * files when they reach a certain size.
  190. *
  191. * <h3>Properties</h3>
  192. * <p>Properties additional to {@link FileAppender}'s properties:
  193. *
  194. * <dl>
  195. * <dt><tt>MaxFileSize</tt></dt>
  196. * <dd>This property specifies maximal size of output file. The
  197. * value is in bytes. It is possible to use <tt>MB</tt> and
  198. * <tt>KB</tt> suffixes to specify the value in megabytes or
  199. * kilobytes instead.</dd>
  200. *
  201. * <dt><tt>MaxBackupIndex</tt></dt>
  202. * <dd>This property limits the number of backup output
  203. * files; e.g. how many <tt>log.1</tt>, <tt>log.2</tt> etc. files
  204. * will be kept.</dd>
  205. * </dl>
  206. */
  207. class LOG4CPLUS_EXPORT RollingFileAppender : public FileAppender {
  208. public:
  209. // Ctors
  210. RollingFileAppender(const log4cplus::tstring& filename,
  211. long maxFileSize = 10*1024*1024, // 10 MB
  212. int maxBackupIndex = 1,
  213. bool immediateFlush = true,
  214. bool createDirs = false);
  215. RollingFileAppender(const log4cplus::helpers::Properties& properties);
  216. // Dtor
  217. virtual ~RollingFileAppender();
  218. protected:
  219. virtual void append(const spi::InternalLoggingEvent& event);
  220. void rollover(bool alreadyLocked = false);
  221. // Data
  222. long maxFileSize;
  223. int maxBackupIndex;
  224. private:
  225. LOG4CPLUS_PRIVATE void init(long maxFileSize, int maxBackupIndex);
  226. };
  227. typedef helpers::SharedObjectPtr<RollingFileAppender>
  228. SharedRollingFileAppenderPtr;
  229. enum DailyRollingFileSchedule { MONTHLY, WEEKLY, DAILY,
  230. TWICE_DAILY, HOURLY, MINUTELY};
  231. /**
  232. * DailyRollingFileAppender extends {@link FileAppender} so that the
  233. * underlying file is rolled over at a user chosen frequency.
  234. *
  235. * <h3>Properties</h3>
  236. * <p>Properties additional to {@link FileAppender}'s properties:
  237. *
  238. * <dl>
  239. * <dt><tt>Schedule</tt></dt>
  240. * <dd>This property specifies rollover schedule. The possible
  241. * values are <tt>MONTHLY</tt>, <tt>WEEKLY</tt>, <tt>DAILY</tt>,
  242. * <tt>TWICE_DAILY</tt>, <tt>HOURLY</tt> and
  243. * <tt>MINUTELY</tt>.</dd>
  244. *
  245. * <dt><tt>MaxBackupIndex</tt></dt>
  246. * <dd>This property limits how many backup files are kept per
  247. * single logging period; e.g. how many <tt>log.2009-11-07.1</tt>,
  248. * <tt>log.2009-11-07.2</tt> etc. files are kept.</dd>
  249. *
  250. * <dt><tt>RollOnClose</tt></dt>
  251. * <dd>This property specifies whether to rollover log files upon
  252. * shutdown. By default it's set to <code>true</code> to retain compatibility
  253. * with legacy code, however it may lead to undesired behaviour
  254. * as described in the github issue #120.</dd>
  255. *
  256. * <dt><tt>DatePattern</tt></dt>
  257. * <dd>This property specifies filename suffix pattern to use for
  258. * periodical backups of the logfile. The patern should be in
  259. * format supported by {@link log4cplus::helpers::Time::getFormatterTime()}</code>.
  260. * Please notice that the format of the pattern is similar but not identical
  261. * to the one used for this option in the corresponding Log4J class.
  262. * If the property isn't specified a reasonable default for a given
  263. * schedule type is used.</dd>
  264. *
  265. * </dl>
  266. */
  267. class LOG4CPLUS_EXPORT DailyRollingFileAppender : public FileAppender {
  268. public:
  269. // Ctors
  270. DailyRollingFileAppender(const log4cplus::tstring& filename,
  271. DailyRollingFileSchedule schedule = DAILY,
  272. bool immediateFlush = true,
  273. int maxBackupIndex = 10,
  274. bool createDirs = false,
  275. bool rollOnClose = true,
  276. const log4cplus::tstring& datePattern = log4cplus::tstring());
  277. DailyRollingFileAppender(const log4cplus::helpers::Properties& properties);
  278. // Dtor
  279. virtual ~DailyRollingFileAppender();
  280. // Methods
  281. virtual void close();
  282. protected:
  283. virtual void append(const spi::InternalLoggingEvent& event);
  284. void rollover(bool alreadyLocked = false);
  285. log4cplus::helpers::Time calculateNextRolloverTime(const log4cplus::helpers::Time& t) const;
  286. log4cplus::tstring getFilename(const log4cplus::helpers::Time& t) const;
  287. // Data
  288. DailyRollingFileSchedule schedule;
  289. log4cplus::tstring scheduledFilename;
  290. log4cplus::helpers::Time nextRolloverTime;
  291. int maxBackupIndex;
  292. bool rollOnClose;
  293. log4cplus::tstring datePattern;
  294. private:
  295. LOG4CPLUS_PRIVATE void init(DailyRollingFileSchedule schedule);
  296. };
  297. typedef helpers::SharedObjectPtr<DailyRollingFileAppender>
  298. SharedDailyRollingFileAppenderPtr;
  299. /**
  300. * TimeBasedRollingFileAppender extends {@link FileAppenderBase} so that
  301. * the underlying file is rolled over at a user chosen frequency while also
  302. * keeping in check a total maximum number of produced files.
  303. *
  304. * <h3>Properties</h3>
  305. * <p>Properties additional to {@link FileAppenderBase}'s properties:
  306. *
  307. * <dl>
  308. *
  309. * <dt><tt>FilenamePattern</tt></dt>
  310. * <dd>The mandatory fileNamePattern property defines the name of the
  311. * rolled-over (archived) log files. Its value should consist of the name
  312. * of the file, plus a suitably placed %d conversion specifier. The %d
  313. * conversion specifier may contain a date-and-time pattern as specified by
  314. * the java's SimpleDateFormat. The rollover period is inferred from the
  315. * value of fileNamePattern.</dd>
  316. *
  317. * <dt><tt>MaxHistory</tt></dt>
  318. * <dd>The optional maxHistory property controls the maximum number of
  319. * archive files to keep, deleting older files.</dd>
  320. *
  321. * <dt><tt>CleanHistoryOnStart</tt></dt>
  322. * <dd>If set to true, archive removal will be executed on appender start
  323. * up. By default this property is set to false. </dd>
  324. *
  325. * <dt><tt>RollOnClose</tt></dt>
  326. * <dd>This property specifies whether to rollover log files upon
  327. * shutdown. By default it's set to <code>true</code> to retain compatibility
  328. * with legacy code, however it may lead to undesired behaviour
  329. * as described in the github issue #120.</dd>
  330. *
  331. * </dl>
  332. */
  333. class LOG4CPLUS_EXPORT TimeBasedRollingFileAppender : public FileAppenderBase {
  334. public:
  335. // Ctors
  336. TimeBasedRollingFileAppender(const tstring& filename = LOG4CPLUS_TEXT(""),
  337. const tstring& filenamePattern = LOG4CPLUS_TEXT("%d.log"),
  338. int maxHistory = 10,
  339. bool cleanHistoryOnStart = false,
  340. bool immediateFlush = true,
  341. bool createDirs = false,
  342. bool rollOnClose = true);
  343. TimeBasedRollingFileAppender(const helpers::Properties& properties);
  344. // Dtor
  345. ~TimeBasedRollingFileAppender();
  346. protected:
  347. void append(const spi::InternalLoggingEvent& event);
  348. void open(std::ios_base::openmode mode);
  349. void close();
  350. void rollover(bool alreadyLocked = false);
  351. void clean(helpers::Time time);
  352. int getRolloverPeriodDuration() const;
  353. helpers::Time calculateNextRolloverTime(const helpers::Time& t) const;
  354. // Data
  355. tstring filenamePattern;
  356. DailyRollingFileSchedule schedule;
  357. tstring scheduledFilename;
  358. int maxHistory;
  359. bool cleanHistoryOnStart;
  360. helpers::Time lastHeartBeat;
  361. helpers::Time nextRolloverTime;
  362. bool rollOnClose;
  363. private:
  364. LOG4CPLUS_PRIVATE void init();
  365. };
  366. typedef helpers::SharedObjectPtr<TimeBasedRollingFileAppender>
  367. SharedTimeBasedRollingFileAppenderPtr;
  368. } // end namespace log4cplus
  369. #endif // LOG4CPLUS_FILE_APPENDER_HEADER_