00001
00002
00003
00004
00005
00006
00007
00008
00009
00010 #include "PortabilityImpl.hh"
00011 #ifdef LOG4CPP_HAVE_IO_H
00012 # include <io.h>
00013 #endif
00014 #ifdef LOG4CPP_HAVE_UNISTD_H
00015 # include <unistd.h>
00016 #endif
00017
00018 #include <memory>
00019 #include <stdio.h>
00020 #include <time.h>
00021 #include <log4cpp/FileAppender.hh>
00022 #include <log4cpp/Category.hh>
00023 #include <log4cpp/FactoryParams.hh>
00024
00025 namespace log4cpp {
00026
00027 FileAppender::FileAppender(const std::string& name,
00028 const std::string& fileName,
00029 bool append,
00030 mode_t mode) :
00031 LayoutAppender(name),
00032 _fileName(fileName),
00033 _flags(O_CREAT | O_APPEND | O_WRONLY),
00034 _mode(mode) {
00035 if (!append)
00036 _flags |= O_TRUNC;
00037 _fd = ::open(_fileName.c_str(), _flags, _mode);
00038 }
00039
00040 FileAppender::FileAppender(const std::string& name, int fd) :
00041 LayoutAppender(name),
00042 _fileName(""),
00043 _fd(fd),
00044 _flags(O_CREAT | O_APPEND | O_WRONLY),
00045 _mode(00644) {
00046 }
00047
00048 FileAppender::~FileAppender() {
00049 close();
00050 }
00051
00052 void FileAppender::close() {
00053 if (_fd!=-1) {
00054 ::close(_fd);
00055 _fd=-1;
00056 }
00057 }
00058
00059 void FileAppender::setAppend(bool append) {
00060 if (append) {
00061 _flags &= ~O_TRUNC;
00062 } else {
00063 _flags |= O_TRUNC;
00064 }
00065 }
00066
00067 bool FileAppender::getAppend() const {
00068 return (_flags & O_TRUNC) == 0;
00069 }
00070
00071 void FileAppender::setMode(mode_t mode) {
00072 _mode = mode;
00073 }
00074
00075 mode_t FileAppender::getMode() const {
00076 return _mode;
00077 }
00078
00079 void FileAppender::_append(const LoggingEvent& event) {
00080 std::string message(_getLayout().format(event));
00081 if (!::write(_fd, message.data(), message.length())) {
00082
00083 }
00084 }
00085
00086 bool FileAppender::reopen() {
00087 if (_fileName != "") {
00088 int fd = ::open(_fileName.c_str(), _flags, _mode);
00089 if (fd < 0)
00090 return false;
00091 else {
00092 if (_fd != -1)
00093 ::close(_fd);
00094 _fd = fd;
00095 return true;
00096 }
00097 } else {
00098 return true;
00099 }
00100 }
00101
00102 std::auto_ptr<Appender> create_file_appender(const FactoryParams& params)
00103 {
00104 std::string name, filename;
00105 bool append = true;
00106 mode_t mode = 664;
00107
00108 params.get_for("file appender").required("name", name)("filename", filename)
00109 .optional("append", append)("mode", mode);
00110
00111 return std::auto_ptr<Appender>(new FileAppender(name, filename, append, mode));
00112 }
00113 }