void OutputStreamWriter::write(const LogString& str, Pool& p) {
  if (str.length() > 0) {
    enum { BUFSIZE = 1024 };
    char rawbuf[BUFSIZE];
    ByteBuffer buf(rawbuf, (size_t) BUFSIZE);
    enc->reset();
    LogString::const_iterator iter = str.begin();
    while(iter != str.end()) {
      CharsetEncoder::encode(enc, str, iter, buf);
      buf.flip();
      out->write(buf, p);
      buf.clear();
    }
    CharsetEncoder::encode(enc, str, iter, buf);
    enc->flush(buf);
    buf.flip();
    out->write(buf, p);
  }
}
    /**
     * Abbreviate element of name.
     * @param buf buffer to receive element.
     * @param startPos starting index of name element.
     * @return starting index of next element.
     */
    LogString::size_type abbreviate(LogString& buf, LogString::size_type startPos) const {
      LogString::size_type nextDot = buf.find(0x2E /* '.' */, startPos);

      if (nextDot != LogString::npos) {
        if ((nextDot - startPos) > charCount) {
          buf.erase(buf.begin() + (startPos + charCount), buf.begin() + nextDot);
          nextDot = startPos + charCount;

          if (ellipsis != 0x00) {
            buf.insert(nextDot, 1, ellipsis);
            nextDot++;
          }
        }

        nextDot++;
      }

      return nextDot;
    }
 virtual log4cxx_status_t decode(ByteBuffer& in,
     LogString& out) {
     size_t remaining = in.remaining();
 if( remaining > 0) {
  const logchar* src = (const logchar*) (in.data() + in.position());
  size_t count = remaining / sizeof(logchar);
  out.append(src, count);
  in.position(in.position() + remaining);
 }
     return APR_SUCCESS;
 }
 LogString format(const LogString& pattern,
     const ObjectPtr& obj) {
     std::vector<PatternConverterPtr> converters;
     std::vector<FormattingInfoPtr> fields;
     PatternMap rules;
     rules.insert(PatternMap::value_type(LOG4CXX_STR("d"), (PatternConstructor) FileDatePatternConverter::newInstance));
     rules.insert(PatternMap::value_type(LOG4CXX_STR("i"), (PatternConstructor) IntegerPatternConverter::newInstance));
     PatternParser::parse(pattern, converters, fields, rules);
     LogString result;
     Pool pool;
     std::vector<FormattingInfoPtr>::const_iterator fieldIter = fields.begin();
     for(std::vector<PatternConverterPtr>::const_iterator converterIter = converters.begin();
         converterIter != converters.end();
         converterIter++, fieldIter++) {
         LogString::size_type i = result.length();
         (*converterIter)->format(obj, result, pool);
         (*fieldIter)->format(i, result);
     }
     return result;
 }
void Logger::removeAppender(const LogString& name1)
{
        synchronized sync(mutex);

        if(name1.empty() || aai == 0)
        {
                return;
        }

        aai->removeAppender(name1);
}
AppenderPtr Logger::getAppender(const LogString& name1) const
{
        synchronized sync(mutex);

        if (aai == 0 || name1.empty())
        {
                return 0;
        }

        return aai->getAppender(name1);
}
    /**
     * Abbreviate name.
     * @param buf buffer that abbreviated name is appended.
     * @param nameStart start of name.
     */
    void abbreviate(LogString::size_type nameStart, LogString& buf) const {
      //
      //  all non-terminal patterns are executed once
      //
      LogString::size_type pos = nameStart;

      for (LogString::size_type i = 0; (i < (fragments.size() - 1)) && (pos < buf.length());
          i++) {
        pos = fragments[i].abbreviate(buf, pos);
      }

      //
      //   last pattern in executed repeatedly
      //
      PatternAbbreviatorFragment terminalFragment =
        fragments[fragments.size() - 1];

      while (pos < buf.length()) {
        pos = terminalFragment.abbreviate(buf, pos);
      }
    }
bool StringHelper::endsWith(const LogString& s, const LogString& suffix)
{
    if (suffix.length() <= s.length()) {
      return s.compare(s.length() - suffix.length(), suffix.length(), suffix) == 0;
    }
    return false;
}
void PropertiesPatternConverter::format(
  const LoggingEventPtr& event,
  LogString& toAppendTo,
  Pool& /* p */) const {
    if (option.length() == 0) {
      toAppendTo.append(1, (logchar) 0x7B /* '{' */);

      LoggingEvent::KeySet keySet(event->getMDCKeySet());

      for(LoggingEvent::KeySet::const_iterator iter = keySet.begin();
          iter != keySet.end();
          iter++) {
          toAppendTo.append(1, (logchar) 0x7B /* '{' */);
          toAppendTo.append(*iter);
          toAppendTo.append(1, (logchar) 0x2C /* ',' */);
          event->getMDC(*iter, toAppendTo);
          toAppendTo.append(1, (logchar) 0x7D /* '}' */);
      }

      toAppendTo.append(1, (logchar) 0x7D /* '}' */);

    } else {
      event->getMDC(option, toAppendTo);
    }
 }
Beispiel #10
0
/**
 * Gets maximum cache validity for the specified SimpleDateTime
 *    conversion pattern.
 *  @param pattern conversion pattern, may not be null.
 *  @returns Duration in microseconds from an integral second
 *      that the cache will return consistent results.
 */
int CachedDateFormat::getMaximumCacheValidity(const LogString& pattern) {
   //
   //   If there are more "S" in the pattern than just one "SSS" then
   //      (for example, "HH:mm:ss,SSS SSS"), then set the expiration to
   //      one millisecond which should only perform duplicate request caching.
   //
   const logchar S = 0x53;
   const logchar SSS[] = { 0x53, 0x53, 0x53, 0 };
   size_t firstS = pattern.find(S);
   size_t len = pattern.length();
   //
   //   if there are no S's or
   //      three that start with the first S and no fourth S in the string
   //
   if (firstS == LogString::npos ||
       (len >= firstS + 3 && pattern.compare(firstS, 3, SSS) == 0
           && (len == firstS + 3 ||
                pattern.find(S, firstS + 3) == LogString::npos))) {
           return 1000000;
   }
   return 1000;
}
Beispiel #11
0
bool NDC::get(LogString& dest)
{
    ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
    if (data != 0) {
        Stack& stack = data->getStack();
        if(!stack.empty()) {
                dest.append(getFullMessage(stack.top()));
                return true;
        }
        data->recycle();
    }
    return false;
}
LevelPtr OptionConverter::toLevel(const LogString& value,
        const LevelPtr& defaultValue)
{
    size_t hashIndex = value.find(LOG4CXX_STR("#"));

        if (hashIndex == LogString::npos)
        {
                if (value.empty())
                {
                        return defaultValue;
                }
                else
                {
                        LogLog::debug(
                ((LogString) LOG4CXX_STR("OptionConverter::toLevel: no class name specified, level=["))
                         + value
                         +LOG4CXX_STR("]"));
                        // no class name specified : use standard Level class
                        return Level::toLevelLS(value, defaultValue);
                }
        }

        LogString clazz = value.substr(hashIndex + 1);
        LogString levelName = value.substr(0, hashIndex);
        LogLog::debug(((LogString) LOG4CXX_STR("OptionConverter::toLevel: class=["))
           + clazz + LOG4CXX_STR("], level=[") + levelName + LOG4CXX_STR("]"));

        // This is degenerate case but you never know.
        if (levelName.empty())
        {
                return Level::toLevelLS(value, defaultValue);
        }

        try
        {
                Level::LevelClass& levelClass =
                        (Level::LevelClass&)Loader::loadClass(clazz);
                return levelClass.toLevel(levelName);
        }
        catch (ClassNotFoundException&)
        {
                LogLog::warn(((LogString) LOG4CXX_STR("custom level class ["))
                   + clazz + LOG4CXX_STR("] not found."));
        }
        catch(Exception& oops)
        {
                LogLog::warn(
                        LOG4CXX_STR("class [") + clazz + LOG4CXX_STR("], level [") + levelName +
                        LOG4CXX_STR("] conversion) failed."), oops);
        }
        catch(...)
        {
                LogLog::warn(
                        LOG4CXX_STR("class [") + clazz + LOG4CXX_STR("], level [") + levelName +
                        LOG4CXX_STR("] conversion) failed."));
        }

        return defaultValue;
}
LogString OptionConverter::getSystemProperty(const LogString& key, const LogString& def)
{
        if (!key.empty())
        {
                LogString value(System::getProperty(key));

                if (!value.empty())
                {
                        return value;
                }
        }
        return def;
}
LogString OptionConverter::convertSpecialChars(const LogString& s)
{
    logchar c;
    LogString sbuf;

    LogString::const_iterator i = s.begin();
    while(i != s.end())
        {
                c = *i++;
                if (c == 0x5C /* '\\' */)
                {
                        c =  *i++;

                        switch (c)
                        {
                        case 0x6E: //'n'
                                c = 0x0A;
                                break;

                        case 0x72: //'r'
                                c = 0x0D;
                                break;

                        case 0x74: //'t'
                                c = 0x09;
                                break;

                        case 0x66: //'f'
                                c = 0x0C;
                                break;
                        default:
                                break;
                        }
                }
                sbuf.append(1, c);
    }
    return sbuf;
}
long OptionConverter::toFileSize(const LogString& s, long dEfault)
{
        if(s.empty())
        {
                return dEfault;
        }

        size_t index = s.find_first_of(LOG4CXX_STR("bB"));
        if (index != LogString::npos && index > 0) {
          long multiplier = 1;
          index--;
          if (s[index] == 0x6B /* 'k' */ || s[index] == 0x4B /* 'K' */) {
                multiplier = 1024;
          } else if(s[index] == 0x6D /* 'm' */ || s[index] == 0x4D /* 'M' */) {
                multiplier = 1024*1024;
          } else if(s[index] == 0x67 /* 'g'*/ || s[index] == 0x47 /* 'G' */) {
                multiplier = 1024*1024*1024;
          }
          return toInt(s.substr(0, index), 1) * multiplier;
        }

        return toInt(s, 1);
}
Beispiel #16
0
LevelPtr ScriptLevel::toLevelLS(const LogString& sArg, const LevelPtr& defaultLevel)
{
   if (sArg.empty())
    {
       return defaultLevel;
    }

    if (StringHelper::equalsIgnoreCase(sArg,
          LOG4CXX_STR("SCRIPT"), LOG4CXX_STR("script"))) {
      return getScript();
    }

    return Level::toLevel(sArg, defaultLevel);
}
void PropertySetter::setProperty(const LogString& option,
                                 const LogString& value,
                                 Pool&)
{
        if (value.empty())
                return;

        if (obj != 0 && obj->instanceof(OptionHandler::getStaticClass()))
        {
                LogLog::debug(LOG4CXX_STR("Setting option name=[") +
                        option + LOG4CXX_STR("], value=[") + value + LOG4CXX_STR("]"));
                OptionHandlerPtr(obj)->setOption(option, value);
        }
}
void OptionConverter::selectAndConfigure(const File& configFileName,
         const LogString& _clazz, spi::LoggerRepositoryPtr& hierarchy)
{
        ConfiguratorPtr configurator;
        LogString clazz = _clazz;

        LogString filename(configFileName.getPath());
        if(clazz.empty() 
                && filename.length() > 4
                && StringHelper::equalsIgnoreCase(
                   filename.substr(filename.length() -4), 
                   LOG4CXX_STR(".XML"), LOG4CXX_STR(".xml")))
        {
            clazz = log4cxx::xml::DOMConfigurator::getStaticClass().toString();
        }

        if(!clazz.empty())
        {
                LogLog::debug(LOG4CXX_STR("Preferred configurator class: ") + clazz);
                configurator = instantiateByClassName(clazz,
                        Configurator::getStaticClass(),
                        0);
                if(configurator == 0)
                {
                        LogLog::error(LOG4CXX_STR("Could not instantiate configurator [")
                                 + clazz + LOG4CXX_STR("]."));
                        return;
                }
        }
        else
        {
                configurator = new PropertyConfigurator();
        }

        configurator->doConfigure(configFileName, hierarchy);
}
void StringHelper::toString(log4cxx_int64_t n, Pool& pool, LogString& dst) {
  if (n >= INT_MIN && n <= INT_MAX) {
    toString((int) n, pool, dst);
  } else {
    const log4cxx_int64_t BILLION = APR_INT64_C(1000000000);
    int billions = (int) (n / BILLION);
    char* upper = pool.itoa(billions);
    int remain = (int) (n - billions * BILLION);
    if (remain < 0) remain *= -1;
    char* lower = pool.itoa(remain);
    Transcoder::decode(upper, dst);
    dst.append(9 - strlen(lower), 0x30 /* '0' */);
    Transcoder::decode(lower, dst);
  }
}
void PatternLayout::format(LogString& output,
      const spi::LoggingEventPtr& event,
      Pool& pool) const
{
  std::vector<FormattingInfoPtr>::const_iterator formatterIter =
     patternFields.begin();
  for(std::vector<LoggingEventPatternConverterPtr>::const_iterator
           converterIter = patternConverters.begin();
      converterIter != patternConverters.end();
      converterIter++, formatterIter++) {
      int startField = output.length();
      (*converterIter)->format(event, output, pool);
      (*formatterIter)->format(startField, output);
  }

}
void SyslogAppender::setFacility(const LogString& facilityName)
{
        if (facilityName.empty())
        {
                return;
        }

        syslogFacility = getFacility(facilityName);
        if (syslogFacility == LOG_UNDEF)
        {
                LogLog::error(LOG4CXX_STR("[")+facilityName +
                                LOG4CXX_STR("] is an unknown syslog facility. Defaulting to [USER]."));
                syslogFacility = LOG_USER;
        }

        this->initSyslogFacilityStr();
}
void SyslogAppender::setSyslogHost(const LogString& syslogHost1)
{
        if (this->sw != 0)
        {
                delete this->sw;
                this->sw = 0;
        }

// On the local host, we can directly use the system function 'syslog'
// if it is available (cf. append)
#if LOG4CXX_HAVE_SYSLOG
        if (syslogHost1 != LOG4CXX_STR("localhost") && syslogHost1 != LOG4CXX_STR("127.0.0.1")
        && !syslogHost1.empty())
#endif
                this->sw = new SyslogWriter(syslogHost1);

        this->syslogHost = syslogHost1;
}
void AppenderAttachableImpl::removeAppender(const LogString& name)
{
        if (name.empty())
        {
                return;
        }

        AppenderList::iterator it, itEnd = appenderList.end();
        AppenderPtr appender;
        for(it = appenderList.begin(); it != itEnd; it++)
        {
                appender = *it;
                if(name == appender->getName())
                {
                        appenderList.erase(it);
                        return;
                }
        }
}
AppenderPtr AppenderAttachableImpl::getAppender(const LogString& name) const
{
        if (name.empty())
        {
                return 0;
        }

        AppenderList::const_iterator it, itEnd = appenderList.end();
        AppenderPtr appender;
        for(it = appenderList.begin(); it != itEnd; it++)
        {
                appender = *it;
                if(name == appender->getName())
                {
                        return appender;
                }
        }

        return 0;
}
/**
 * {@inheritDoc}
 */
RolloverDescriptionPtr FixedWindowRollingPolicy::initialize(
  const LogString& file, bool append, log4cxx::helpers::Pool& p) {
  LogString newActiveFile(file);
  explicitActiveFile = false;

  if (file.length() > 0) {
    explicitActiveFile = true;
    newActiveFile = file;
  }

  if (!explicitActiveFile) {
    LogString buf;
    ObjectPtr obj(new Integer(minIndex));
    formatFileName(obj, buf, p);
    newActiveFile = buf;
  }

  ActionPtr noAction;

  return new RolloverDescription(newActiveFile, append, noAction, noAction);
}
Beispiel #26
0
LevelPtr Level::toLevelLS(const LogString& sArg, const LevelPtr& defaultLevel)
{
    const size_t len = sArg.length();

    if (len == 4) {
      if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("INFO"), LOG4CXX_STR("info"))) {
        return getInfo();
      }
      if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("WARN"), LOG4CXX_STR("warn"))) {
        return getWarn();
      }
    } else {
      if (len == 5) {
        if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("DEBUG"), LOG4CXX_STR("debug"))) {
          return getDebug();
        }
        if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("TRACE"), LOG4CXX_STR("trace"))) {
          return getTrace();
        }
        if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("ERROR"), LOG4CXX_STR("error"))) {
          return getError();
        }
        if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("FATAL"), LOG4CXX_STR("fatal"))) {
          return getFatal();
        }
      } else {
        if (len == 3) {
          if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("OFF"), LOG4CXX_STR("off"))) {
            return getOff();
          }
          if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("ALL"), LOG4CXX_STR("all"))) {
            return getAll();
          }
        }
      }
    }

    return defaultLevel;
}
              virtual log4cxx_status_t decode(ByteBuffer& in,
                  LogString& out) {
                  log4cxx_status_t stat = APR_SUCCESS;
                  enum { BUFSIZE = 256 };
                  wchar_t buf[BUFSIZE];

                  mbstate_t mbstate;
                  memset(&mbstate, 0, sizeof(mbstate));

                  while(in.remaining() > 0) {
                      size_t requested = in.remaining();
                      if (requested > BUFSIZE - 1) {
                          requested = BUFSIZE - 1;
                      }

                      memset(buf, 0, BUFSIZE*sizeof(wchar_t));
                      const char* src = in.current();
                      if(*src == 0) {
                           out.append(1, (logchar) 0);
                           in.position(in.position() + 1);
                      } else {
                           size_t converted = mbsrtowcs(buf,
                               &src,
                               requested,
                               &mbstate);
                           if (converted == (size_t) -1) {
                               stat = APR_BADARG;
                               in.position(src - in.data());
                               break;
                           } else {
                               stat = append(out, buf);
                               in.position(in.position() + converted);
                           }
                      }
                  }
                  return stat;
              }
ObjectPtr OptionConverter::instantiateByClassName(const LogString& className,
        const Class& superClass, const ObjectPtr& defaultValue)
{
        if(!className.empty())
        {
                try
                {
                        const Class& classObj = Loader::loadClass(className);
                        ObjectPtr newObject =  classObj.newInstance();
                        if (!newObject->instanceof(superClass))
                        {
                                return defaultValue;
                        }

                        return newObject;
                }
                catch (Exception& e)
                {
                        LogLog::error(LOG4CXX_STR("Could not instantiate class [") +
                                className + LOG4CXX_STR("]."), e);
                }
        }
        return defaultValue;
}
void LevelPatternConverter::format(
  const LoggingEventPtr& event,
  LogString& toAppendTo,
  log4cxx::helpers::Pool& /* p */) const {
   toAppendTo.append(event->getLevel()->toString());
 }
/**
 * Purge and rename old log files in preparation for rollover
 * @param lowIndex low index
 * @param highIndex high index.  Log file associated with high
 * index will be deleted if needed.
 * @return true if purge was successful and rollover should be attempted.
 */
bool FixedWindowRollingPolicy::purge(int lowIndex, int highIndex, Pool& p) const {
  int suffixLength = 0;

  std::vector<FileRenameActionPtr> renames;
  LogString buf;
  ObjectPtr obj = new Integer(lowIndex);
  formatFileName(obj, buf, p);

  LogString lowFilename(buf);

  if (lowFilename.compare(lowFilename.length() - 3, 3, LOG4CXX_STR(".gz")) == 0) {
    suffixLength = 3;
  } else if (lowFilename.compare(lowFilename.length() - 4, 4, LOG4CXX_STR(".zip")) == 0) {
    suffixLength = 4;
  }

  for (int i = lowIndex; i <= highIndex; i++) {
    File toRenameCompressed;
    toRenameCompressed.setPath(lowFilename);
    File toRenameBase;
    toRenameBase.setPath(lowFilename.substr(0, lowFilename.length() - suffixLength));
    File* toRename = &toRenameCompressed;
    bool isBase = false;
    bool exists = toRenameCompressed.exists(p);

    if (suffixLength > 0) {
      if (exists) {
        if (toRenameBase.exists(p)) {
          toRenameBase.deleteFile(p);
        }
      } else {
        toRename = &toRenameBase;
        exists = toRenameBase.exists(p);
        isBase = true;
      }
    }

    if (exists) {
      //
      //    if at upper index then
      //        attempt to delete last file
      //        if that fails then abandon purge
      if (i == highIndex) {
        if (!toRename->deleteFile(p)) {
          return false;
        }

        break;
      }

      //
      //   if intermediate index
      //     add a rename action to the list
      buf.erase(buf.begin(), buf.end());
      obj = new Integer(i + 1);
      formatFileName(obj, buf, p);

      LogString highFilename(buf);
      LogString renameTo(highFilename);

      if (isBase) {
        renameTo =
          highFilename.substr(0, highFilename.length() - suffixLength);
      }

      renames.push_back(new FileRenameAction(*toRename, File().setPath(renameTo), true));
      lowFilename = highFilename;
    } else {
      break;
    }
  }

  //
  //   work renames backwards
  //
  for(std::vector<FileRenameActionPtr>::reverse_iterator iter = renames.rbegin();
      iter != renames.rend();
      iter++) {

     try {
         if (!(*iter)->execute(p)) {
            return false;
         }
     } catch (std::exception& ) {
        LogLog::warn(LOG4CXX_STR("Exception during purge in RollingFileAppender"));

        return false;
     }
  }
  return true;
}