code stringlengths 1 2.06M | language stringclasses 1 value |
|---|---|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _LOG4CXX_PATTERN_FILE_DATE_PATTERN_CONVERTER
#define _LOG4CXX_PATTERN_FILE_DATE_PATTERN_CONVERTER
#include <log4cxx/pattern/patternconverter.h>
namespace log4cxx { namespace pattern {
/**
* Formats an date by delegating to DatePatternConverter. The default
* date pattern for a %d specifier in a file name is different than
* the %d pattern in pattern layout.
*
*
*
*/
class LOG4CXX_EXPORT FileDatePatternConverter {
/**
* Private constructor.
*/
FileDatePatternConverter();
public:
/**
* Obtains an instance of pattern converter.
* @param options options, may be null.
* @return instance of pattern converter.
*/
static PatternConverterPtr newInstance(
const std::vector<LogString>& options);
};
}
}
#endif
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _LOG4CXX_PATTERN_LINE_LOCATION_PATTERN_CONVERTER
#define _LOG4CXX_PATTERN_LINE_LOCATION_PATTERN_CONVERTER
#include <log4cxx/pattern/loggingeventpatternconverter.h>
namespace log4cxx {
namespace pattern {
/**
* Format the event's line location information.
*
*
*
*/
class LOG4CXX_EXPORT LineLocationPatternConverter
: public LoggingEventPatternConverter {
/**
* Private constructor.
*/
LineLocationPatternConverter();
public:
DECLARE_LOG4CXX_PATTERN(LineLocationPatternConverter)
BEGIN_LOG4CXX_CAST_MAP()
LOG4CXX_CAST_ENTRY(LineLocationPatternConverter)
LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter)
END_LOG4CXX_CAST_MAP()
/**
* Obtains an instance of pattern converter.
* @param options options, may be null.
* @return instance of pattern converter.
*/
static PatternConverterPtr newInstance(
const std::vector<LogString>& options);
void format(const log4cxx::spi::LoggingEventPtr& event,
LogString& toAppendTo,
log4cxx::helpers::Pool& p) const;
};
}
}
#endif
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _LOG4CXX_HELPER_PATTERN_CONVERTER_H
#define _LOG4CXX_HELPER_PATTERN_CONVERTER_H
#if defined(_MSC_VER)
#pragma warning (push)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <map>
#include <vector>
#include <log4cxx/helpers/class.h>
#include <log4cxx/pattern/patternconverter.h>
#include <log4cxx/pattern/formattinginfo.h>
namespace log4cxx {
namespace pattern {
typedef PatternConverterPtr (*PatternConstructor)(const std::vector<LogString>& options);
typedef std::map<LogString, PatternConstructor> PatternMap;
// Contributors: Nelson Minar <(nelson@monkey.org>
// Igor E. Poteryaev <jah@mail.ru>
// Reinhard Deschler <reinhard.deschler@web.de>
/**
* Most of the work of the {@link log4cxx::PatternLayout PatternLayout} class
* is delegated to the PatternParser class.
* <p>It is this class that parses conversion patterns and creates
* a chained list of {@link PatternConverter PatternConverters}.
*
*
*/
class LOG4CXX_EXPORT PatternParser {
/**
* Escape character for format specifier.
*/
static const logchar ESCAPE_CHAR;
enum {
LITERAL_STATE = 0,
CONVERTER_STATE = 1,
DOT_STATE = 3,
MIN_STATE = 4,
MAX_STATE = 5
};
/**
* Private constructor.
*/
PatternParser();
private:
/** Extract the converter identifier found at position i.
*
* After this function returns, the variable i will point to the
* first char after the end of the converter identifier.
*
* If i points to a char which is not a character acceptable at the
* start of a unicode identifier, the value null is returned.
*
* @param lastChar last processed character.
* @param pattern format string.
* @param i current index into pattern format.
* @param convBuf buffer to receive conversion specifier.
* @param currentLiteral literal to be output in case format specifier in unrecognized.
* @return position in pattern after converter.
*/
static int extractConverter(
logchar lastChar, const LogString& pattern,
LogString::size_type i, LogString& convBuf,
LogString& currentLiteral);
/**
* Extract options.
* @param pattern conversion pattern.
* @param i start of options.
* @param options array to receive extracted options
* @return position in pattern after options.
*/
static int extractOptions(const LogString& pattern, LogString::size_type i,
std::vector<LogString>& options);
public:
/**
* Parse a format specifier.
* @param pattern pattern to parse.
* @param patternConverters list to receive pattern converters.
* @param formattingInfos list to receive field specifiers corresponding to pattern converters.
* @param rules map of stock pattern converters keyed by format specifier.
*/
static void parse(
const LogString& pattern,
std::vector<PatternConverterPtr>& patternConverters,
std::vector<FormattingInfoPtr>& formattingInfos,
const PatternMap& rules);
private:
/**
* Creates a new PatternConverter.
*
*
* @param converterId converterId.
* @param currentLiteral literal to be used if converter is unrecognized or following converter
* if converterId contains extra characters.
* @param rules map of stock pattern converters keyed by format specifier.
* @param options converter options.
* @return converter or null.
*/
static PatternConverterPtr createConverter(
const LogString& converterId,
LogString& currentLiteral,
const PatternMap& rules,
std::vector<LogString>& options);
/**
* Processes a format specifier sequence.
*
* @param c initial character of format specifier.
* @param pattern conversion pattern
* @param i current position in conversion pattern.
* @param currentLiteral current literal.
* @param formattingInfo current field specifier.
* @param rules map of stock pattern converters keyed by format specifier.
* @param patternConverters list to receive parsed pattern converter.
* @param formattingInfos list to receive corresponding field specifier.
* @return position after format specifier sequence.
*/
static int finalizeConverter(
logchar c, const LogString& pattern, int i,
LogString& currentLiteral, const FormattingInfoPtr& formattingInfo,
const PatternMap& rules,
std::vector<PatternConverterPtr>& patternConverters,
std::vector<FormattingInfoPtr>& formattingInfos);
static bool isUnicodeIdentifierStart(logchar c);
static bool isUnicodeIdentifierPart(logchar c);
};
}
}
#if defined(_MSC_VER)
#pragma warning (pop)
#endif
#endif
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _LOG4CXX_BASIC_CONFIGURATOR_H
#define _LOG4CXX_BASIC_CONFIGURATOR_H
#include <log4cxx/helpers/objectptr.h>
#include <log4cxx/helpers/objectimpl.h>
#include <log4cxx/logger.h>
#include <log4cxx/logstring.h>
#include <log4cxx/spi/configurator.h>
namespace log4cxx
{
class Appender;
typedef helpers::ObjectPtrT<Appender> AppenderPtr;
/**
Use this class to quickly configure the package.
<p>For file based configuration see
PropertyConfigurator. For XML based configuration see
DOMConfigurator.
*/
class LOG4CXX_EXPORT BasicConfigurator
{
protected:
BasicConfigurator() {}
public:
/**
Add a ConsoleAppender that uses PatternLayout
using the PatternLayout#TTCC_CONVERSION_PATTERN and
prints to <code>stdout</code> to the root logger.*/
static void configure();
/**
Add <code>appender</code> to the root logger.
@param appender The appender to add to the root logger.
*/
static void configure(const AppenderPtr& appender);
/**
Reset the default hierarchy to its defaut. It is equivalent to
calling
<code>Logger::getDefaultHierarchy()->resetConfiguration()</code>.
See Hierarchy#resetConfiguration() for more details. */
static void resetConfiguration();
}; // class BasicConfigurator
} // namespace log4cxx
#endif //_LOG4CXX_BASIC_CONFIGURATOR_H
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _LOG4CXX_TTCC_LAYOUT_H
#define _LOG4CXX_TTCC_LAYOUT_H
#if defined(_MSC_VER)
#pragma warning ( push )
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/helpers/datelayout.h>
namespace log4cxx
{
/**
TTCC layout format consists of time, thread, logger name and nested
diagnostic context information, hence the name.
<p>Each of the four fields can be individually enabled or
disabled. The time format depends on the <code>DateFormat</code>
used.
<p>Here is an example TTCCLayout output with the
{@link helpers::RelativeTimeDateFormat RelativeTimeDateFormat}.
<pre>
176 [main] INFO examples.Sort - Populating an array of 2 elements in reverse order.
225 [main] INFO examples.SortAlgo - Entered the sort method.
262 [main] DEBUG examples.SortAlgo.OUTER i=1 - Outer loop.
276 [main] DEBUG examples.SortAlgo.SWAP i=1 j=0 - Swapping intArray[0] = 1 and intArray[1] = 0
290 [main] DEBUG examples.SortAlgo.OUTER i=0 - Outer loop.
304 [main] INFO examples.SortAlgo.DUMP - Dump of interger array:
317 [main] INFO examples.SortAlgo.DUMP - Element [0] = 0
331 [main] INFO examples.SortAlgo.DUMP - Element [1] = 1
343 [main] INFO examples.Sort - The next log statement should be an error message.
346 [main] ERROR examples.SortAlgo.DUMP - Tried to dump an uninitialized array.
467 [main] INFO examples.Sort - Exiting main method.
</pre>
<p>The first field is the number of milliseconds elapsed since the
start of the program. The second field is the thread outputting the
log statement. The third field is the level, the fourth field is
the logger to which the statement belongs.
<p>The fifth field (just before the '-') is the nested diagnostic
context. Note the nested diagnostic context may be empty as in the
first two statements. The text after the '-' is the message of the
statement.
<p><b>WARNING</b> Do not use the same TTCCLayout instance from
within different appenders. The TTCCLayout is not thread safe when
used in his way. However, it is perfectly safe to use a TTCCLayout
instance from just one appender.
<p>PatternLayout offers a much more flexible alternative.
*/
class LOG4CXX_EXPORT TTCCLayout : public helpers::DateLayout
{
private:
// Internal representation of options
bool threadPrinting;
bool categoryPrefixing;
bool contextPrinting;
bool filePrinting;
public:
DECLARE_LOG4CXX_OBJECT(TTCCLayout)
BEGIN_LOG4CXX_CAST_MAP()
LOG4CXX_CAST_ENTRY(TTCCLayout)
LOG4CXX_CAST_ENTRY_CHAIN(Layout)
END_LOG4CXX_CAST_MAP()
/**
Instantiate a TTCCLayout object with {@link
helpers::RelativeTimeDateFormat RelativeTimeDateFormat} as the date
formatter in the local time zone.
*/
TTCCLayout();
/**
Instantiate a TTCCLayout object using the local time zone. The
DateFormat used will depend on the <code>dateFormatType</code>.
<p>This constructor just calls the {@link
helpers::DateLayout#setDateFormat DateLayout::setDateFormat} method.
*/
TTCCLayout(const LogString& dateFormatType);
/**
The <b>ThreadPrinting</b> option specifies whether the name of the
current thread is part of log output or not. This is true by default.
*/
inline void setThreadPrinting(bool threadPrinting1)
{ this->threadPrinting = threadPrinting1; }
/**
Returns value of the <b>ThreadPrinting</b> option.
*/
inline bool getThreadPrinting() const
{ return threadPrinting; }
/**
The <b>CategoryPrefixing</b> option specifies whether Logger
name is part of log output or not. This is true by default.
*/
inline void setCategoryPrefixing(bool categoryPrefixing1)
{ this->categoryPrefixing = categoryPrefixing1; }
/**
Returns value of the <b>CategoryPrefixing</b> option.
*/
inline bool getCategoryPrefixing() const
{ return categoryPrefixing; }
/**
The <b>ContextPrinting</b> option specifies log output will include
the nested context information belonging to the current thread.
This is true by default.
*/
inline void setContextPrinting(bool contextPrinting1)
{ this->contextPrinting = contextPrinting1; }
/**
Returns value of the <b>ContextPrinting</b> option.
*/
inline bool getContextPrinting() const
{ return contextPrinting; }
/**
The <b>FilePrinting</b> option specifies log output will include
the file and the line where the log statement was written.
*/
inline void setFilePrinting(bool filePrinting1)
{ this->filePrinting = filePrinting1; }
/**
Returns value of the <b>ContextPrinting</b> option.
*/
inline bool getFilePrinting() const
{ return filePrinting; }
/**
In addition to the level of the statement and message, this function
writes to the ouput stream time, thread, logger and NDC
information.
<p>Time, thread, logger and diagnostic context are printed
depending on options.
@param output destination to receive formatted output.
@param event event to format.
@param pool pool used to allocate memory needed during formatting.
*/
virtual void format(LogString& output,
const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& pool) const;
/**
The TTCCLayout does not handle the throwable contained within
{@link spi::LoggingEvent LoggingEvents}. Thus, it returns
<code>true</code>.
*/
virtual bool ignoresThrowable() const { return true; }
};
LOG4CXX_PTR_DEF(TTCCLayout);
}
#if defined(_MSC_VER)
#pragma warning ( pop )
#endif
#endif
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/simpledateformat.h>
#include <apr_time.h>
#include <apr_strings.h>
#include <sstream>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/helpers/stringhelper.h>
#include <assert.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/private/log4cxx_private.h>
#include <log4cxx/helpers/pool.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace std;
#if LOG4CXX_HAS_STD_LOCALE
#include <locale>
#endif
#if defined(_MSC_VER) && _MSC_VER < 1300
#define HAS_FACET(locale, type) _HAS(locale, type)
#define USE_FACET(locale, type) _USE(locale, type)
#define PUT_FACET(facet, os, time, spec) facet.put(os, os, time, spec)
#else
#if defined(_RWSTD_NO_TEMPLATE_ON_RETURN_TYPE)
#define HAS_FACET(locale, type) std::has_facet(locale, (type*) 0)
#define USE_FACET(locale, type) std::use_facet(locale, (type*) 0)
#else
#define HAS_FACET(locale, type) std::has_facet < type >(locale)
#define USE_FACET(locale, type) std::use_facet < type >(locale)
#endif
#define PUT_FACET(facet, os, time, spec) facet.put(os, os, os.fill(), time, spec)
#endif
namespace log4cxx
{
namespace helpers
{
namespace SimpleDateFormatImpl
{
typedef void (*incrementFunction)(tm& time, apr_time_exp_t& apr_time);
/**
* Abstract inner class representing one format token
* (one or more instances of a character).
*/
class PatternToken {
public:
PatternToken() {
}
virtual ~PatternToken() {
}
/**
* Sets the time zone.
* @param zone new time zone.
*/
virtual void setTimeZone(const TimeZonePtr& zone) {
}
/**
* Appends the formatted content to the string.
* @param s string to which format contribution is appended.
* @param date exploded date/time.
* @param p memory pool.
*/
virtual void format(LogString& s,
const apr_time_exp_t& date,
log4cxx::helpers::Pool& p) const = 0;
protected:
static void incrementMonth(tm& time, apr_time_exp_t& aprtime) {
time.tm_mon++;
aprtime.tm_mon++;
}
static void incrementDay(tm& time, apr_time_exp_t& aprtime) {
time.tm_wday++;
aprtime.tm_wday++;
}
static void incrementHalfDay(tm& time, apr_time_exp_t& aprtime) {
time.tm_hour += 12;
aprtime.tm_hour += 12;
}
static void renderFacet(const std::locale* locale,
incrementFunction inc,
char spec,
unsigned int wspec,
const char* aprspec,
std::vector<LogString>& values) {
std::vector<LogString>::iterator valueIter = values.begin();
tm time;
memset(&time, 0, sizeof(time));
apr_time_exp_t aprtime;
memset(&aprtime, 0, sizeof(aprtime));
#if LOG4CXX_HAS_STD_LOCALE
if (locale != NULL) {
#if LOG4CXX_WCHAR_T_API
if (HAS_FACET(*locale, std::time_put<wchar_t>)) {
const std::time_put<wchar_t>& facet = USE_FACET(*locale, std::time_put<wchar_t>);
size_t start = 0;
std::basic_ostringstream<wchar_t> os;
for(; valueIter != values.end(); valueIter++) {
PUT_FACET(facet, os, &time, (wchar_t) wspec);
Transcoder::decode(os.str().substr(start), *valueIter);
start = os.str().length();
(*inc)(time, aprtime);
}
} else
#endif
if (HAS_FACET(*locale, std::time_put<char>)) {
const std::time_put<char>& facet = USE_FACET(*locale, std::time_put<char> );
size_t start = 0;
std::ostringstream os;
for(; valueIter != values.end(); valueIter++) {
PUT_FACET(facet, os, &time, spec);
Transcoder::decode(os.str().substr(start), *valueIter);
start = os.str().length();
(*inc)(time, aprtime);
}
}
}
#endif
const size_t BUFSIZE = 256;
char buf[BUFSIZE];
memset(buf, 0, BUFSIZE);
apr_size_t retsize = 0;
for(; valueIter != values.end(); valueIter++) {
apr_status_t stat = apr_strftime(buf, &retsize, BUFSIZE, aprspec, &aprtime);
(*inc)(time, aprtime);
if (stat == APR_SUCCESS) {
Transcoder::decode(std::string(buf, retsize), *valueIter);
} else {
valueIter->append(1, (logchar) 0x3F);
}
}
}
private:
/**
* Private copy constructor.
*/
PatternToken(const PatternToken&);
/**
* Private assignment operator.
*/
PatternToken& operator=(const PatternToken&);
};
class LiteralToken : public PatternToken
{
public:
LiteralToken( logchar ch1, int count1 ) : ch( ch1 ), count( count1 )
{
}
void format( LogString& s, const apr_time_exp_t & , Pool & /* p */ ) const
{
s.append( count, ch );
}
private:
logchar ch;
int count;
};
class EraToken : public PatternToken
{
public:
EraToken( int /* count */ , const std::locale * /* locale */ )
{
}
void format(LogString& s, const apr_time_exp_t & /* tm */, Pool & /* p */ ) const
{
s.append(1, (logchar) 0x41 /* 'A' */);
s.append(1, (logchar) 0x44 /* 'D' */);
}
};
class NumericToken : public PatternToken
{
public:
NumericToken( size_t width1 ) : width( width1 )
{
}
virtual int getField( const apr_time_exp_t & tm ) const = 0;
void format( LogString& s, const apr_time_exp_t & tm, Pool & p ) const
{
size_t initialLength = s.length();
StringHelper::toString( getField( tm ), p, s );
size_t finalLength = s.length();
if ( initialLength + width > finalLength )
{
s.insert( initialLength, ( initialLength + width ) - finalLength, (logchar) 0x30 /* '0' */);
}
}
private:
size_t width;
char zeroDigit;
};
class YearToken : public NumericToken
{
public:
YearToken( int width1 ) : NumericToken( width1 )
{
}
int getField( const apr_time_exp_t & tm ) const
{
return 1900 + tm.tm_year;
}
};
class MonthToken : public NumericToken
{
public:
MonthToken( int width1 ) : NumericToken( width1 )
{
}
int getField( const apr_time_exp_t & tm ) const
{
return tm.tm_mon + 1;
}
};
class AbbreviatedMonthNameToken : public PatternToken
{
public:
AbbreviatedMonthNameToken(int, const std::locale *locale) : names( 12 ) {
renderFacet(locale, PatternToken::incrementMonth, 'b', 0x62, "%b", names);
}
void format(LogString& s, const apr_time_exp_t & tm, Pool & /* p */ ) const
{
s.append( names[tm.tm_mon] );
}
private:
std::vector < LogString > names;
};
class FullMonthNameToken : public PatternToken
{
public:
FullMonthNameToken( int width, const std::locale *locale) : names( 12 )
{
renderFacet(locale, PatternToken::incrementMonth, 'B', 0x42, "%B", names);
}
void format( LogString& s, const apr_time_exp_t & tm, Pool & /* p */ ) const
{
s.append( names[tm.tm_mon] );
}
private:
std::vector < LogString > names;
};
class WeekInYearToken : public NumericToken
{
public:
WeekInYearToken( int width1 ) : NumericToken( width1 )
{
}
int getField( const apr_time_exp_t & tm ) const
{
return tm.tm_yday / 7;
}
};
class WeekInMonthToken : public NumericToken
{
public:
WeekInMonthToken( int width1 ) : NumericToken( width1 )
{
}
int getField( const apr_time_exp_t & tm ) const
{
return tm.tm_mday / 7;
}
};
class DayInMonthToken : public NumericToken
{
public:
DayInMonthToken( int width1 ) : NumericToken( width1 )
{
}
int getField( const apr_time_exp_t & tm ) const
{
return tm.tm_mday;
}
};
class DayInYearToken : public NumericToken
{
public:
DayInYearToken( int width1 ) : NumericToken( width1 )
{
}
int getField( const apr_time_exp_t & tm ) const
{
return tm.tm_yday;
}
};
class DayOfWeekInMonthToken : public NumericToken
{
public:
DayOfWeekInMonthToken( int width1 ) : NumericToken( width1 )
{
}
int getField( const apr_time_exp_t & /* tm */ ) const
{
return -1;
}
};
class AbbreviatedDayNameToken : public PatternToken
{
public:
AbbreviatedDayNameToken( int width, const std::locale *locale) : names( 7 ) {
renderFacet(locale, PatternToken::incrementDay, 'a', 0x61, "%a", names);
}
void format( LogString& s, const apr_time_exp_t & tm, Pool & /* p */ ) const
{
s.append( names[tm.tm_wday] );
}
private:
std::vector < LogString > names;
};
class FullDayNameToken : public PatternToken
{
public:
FullDayNameToken( int width, const std::locale *locale) : names( 7 ) {
renderFacet(locale, PatternToken::incrementDay, 'A', 0x41, "%A", names);
}
void format( LogString& s, const apr_time_exp_t & tm, Pool & /* p */ ) const
{
s.append( names[tm.tm_wday] );
}
private:
std::vector < LogString > names;
};
class MilitaryHourToken : public NumericToken
{
public:
MilitaryHourToken( int width1, int offset1 ) : NumericToken( width1 ), offset( offset1 )
{
}
int getField( const apr_time_exp_t & tm ) const
{
return tm.tm_hour + offset;
}
private:
int offset;
};
class HourToken : public NumericToken
{
public:
HourToken( int width1, int /* offset1 */ ) : NumericToken( width1 )
{
}
int getField( const apr_time_exp_t & tm ) const
{
return ( ( tm.tm_hour + 12 - offset ) % 12 ) + offset;
}
private:
int offset;
};
class MinuteToken : public NumericToken
{
public:
MinuteToken( int width1 ) : NumericToken( width1 )
{
}
int getField( const apr_time_exp_t & tm ) const
{
return tm.tm_min;
}
};
class SecondToken : public NumericToken
{
public:
SecondToken( int width1 ) : NumericToken( width1 )
{
}
int getField( const apr_time_exp_t & tm ) const
{
return tm.tm_sec;
}
};
class MillisecondToken : public NumericToken
{
public:
MillisecondToken( int width1 ) : NumericToken( width1 )
{
}
int getField( const apr_time_exp_t & tm ) const
{
return tm.tm_usec / 1000;
}
};
class AMPMToken : public PatternToken
{
public:
AMPMToken( int width, const std::locale *locale) : names( 2 ) {
renderFacet(locale, PatternToken::incrementHalfDay, 'p', 0x70, "%p", names);
}
void format( LogString& s, const apr_time_exp_t & tm, Pool & /* p */ ) const
{
s.append( names[tm.tm_hour / 12] );
}
private:
std::vector < LogString > names;
};
class GeneralTimeZoneToken : public PatternToken
{
public:
GeneralTimeZoneToken( int /* width */ )
{
}
void format( LogString& s, const apr_time_exp_t & , Pool & /* p */ ) const {
s.append(timeZone->getID());
}
void setTimeZone( const TimeZonePtr & zone )
{
timeZone = zone;
}
private:
TimeZonePtr timeZone;
};
class RFC822TimeZoneToken : public PatternToken
{
public:
RFC822TimeZoneToken( int /* width */ )
{
}
void format( LogString& s, const apr_time_exp_t & tm, Pool & p ) const
{
if ( tm.tm_gmtoff == 0 )
{
s.append( 1, (logchar) 0x5A /* 'Z' */ );
}
else
{
apr_int32_t off = tm.tm_gmtoff;
size_t basePos = s.length();
s.append( LOG4CXX_STR( "+0000" ) );
if ( off < 0 )
{
s[basePos] = 0x2D; // '-'
off = -off;
}
LogString hours;
StringHelper::toString( off / 3600, p, hours );
size_t hourPos = basePos + 2;
//
// assumes that point values for 0-9 are same between char and wchar_t
//
for ( size_t i = hours.length(); i-- > 0; )
{
s[hourPos--] = hours[i];
}
LogString min;
StringHelper::toString( ( off % 3600 ) / 60, p, min );
size_t minPos = basePos + 4;
//
// assumes that point values for 0-9 are same between char and wchar_t
//
for ( size_t j = min.length(); j-- > 0; )
{
s[minPos--] = min[j];
}
}
}
};
}
}
}
using namespace log4cxx::helpers::SimpleDateFormatImpl;
void SimpleDateFormat::addToken(const logchar spec, const int repeat, const std::locale * locale,
std::vector < PatternToken * > & pattern )
{
PatternToken * token = NULL;
switch ( spec )
{
case 0x47: // 'G'
token = ( new EraToken( repeat, locale ) );
break;
case 0x79: // 'y'
token = ( new YearToken( repeat ) );
break;
case 0x4D: // 'M'
if ( repeat <= 2 )
{
token = ( new MonthToken( repeat ) );
}
else if ( repeat <= 3 )
{
token = ( new AbbreviatedMonthNameToken( repeat, locale ) );
}
else
{
token = ( new FullMonthNameToken( repeat, locale ) );
}
break;
case 0x77: // 'w'
token = ( new WeekInYearToken( repeat ) );
break;
case 0x57: // 'W'
token = ( new WeekInMonthToken( repeat ) );
break;
case 0x44: // 'D'
token = ( new DayInYearToken( repeat ) );
break;
case 0x64: // 'd'
token = ( new DayInMonthToken( repeat ) );
break;
case 0x46: // 'F'
token = ( new DayOfWeekInMonthToken( repeat ) );
break;
case 0x45: // 'E'
if ( repeat <= 3 )
{
token = ( new AbbreviatedDayNameToken( repeat, locale ) );
}
else
{
token = ( new FullDayNameToken( repeat, locale ) );
}
break;
case 0x61: // 'a'
token = ( new AMPMToken( repeat, locale ) );
break;
case 0x48: // 'H'
token = ( new MilitaryHourToken( repeat, 0 ) );
break;
case 0x6B: // 'k'
token = ( new MilitaryHourToken( repeat, 1 ) );
break;
case 0x4B: // 'K'
token = ( new HourToken( repeat, 0 ) );
break;
case 0x68: // 'h'
token = ( new HourToken( repeat, 1 ) );
break;
case 0x6D: // 'm'
token = ( new MinuteToken( repeat ) );
break;
case 0x73: // 's'
token = ( new SecondToken( repeat ) );
break;
case 0x53: // 'S'
token = ( new MillisecondToken( repeat ) );
break;
case 0x7A: // 'z'
token = ( new GeneralTimeZoneToken( repeat ) );
break;
case 0x5A: // 'Z'
token = ( new RFC822TimeZoneToken( repeat ) );
break;
default:
token = ( new LiteralToken( spec, repeat ) );
}
assert( token != NULL );
pattern.push_back( token );
}
void SimpleDateFormat::parsePattern( const LogString & fmt, const std::locale * locale,
std::vector < PatternToken * > & pattern )
{
if ( !fmt.empty() )
{
LogString::const_iterator iter = fmt.begin();
int repeat = 1;
logchar prevChar = * iter;
for ( iter++; iter != fmt.end(); iter++ )
{
if ( * iter == prevChar )
{
repeat++;
}
else
{
addToken( prevChar, repeat, locale, pattern );
prevChar = * iter;
repeat = 1;
}
}
addToken( prevChar, repeat, locale, pattern );
}
}
SimpleDateFormat::SimpleDateFormat( const LogString & fmt ) : timeZone( TimeZone::getDefault() )
{
#if LOG4CXX_HAS_STD_LOCALE
std::locale defaultLocale;
parsePattern( fmt, & defaultLocale, pattern );
#else
parsePattern( fmt, NULL, pattern );
#endif
for ( PatternTokenList::iterator iter = pattern.begin(); iter != pattern.end(); iter++ )
{
( * iter )->setTimeZone( timeZone );
}
}
SimpleDateFormat::SimpleDateFormat( const LogString & fmt, const std::locale * locale ) : timeZone( TimeZone::getDefault() )
{
parsePattern( fmt, locale, pattern );
for ( PatternTokenList::iterator iter = pattern.begin(); iter != pattern.end(); iter++ )
{
( * iter )->setTimeZone( timeZone );
}
}
SimpleDateFormat::~SimpleDateFormat()
{
for ( PatternTokenList::iterator iter = pattern.begin(); iter != pattern.end(); iter++ )
{
delete * iter;
}
}
void SimpleDateFormat::format( LogString & s, log4cxx_time_t time, Pool & p ) const
{
apr_time_exp_t exploded;
apr_status_t stat = timeZone->explode( & exploded, time );
if ( stat == APR_SUCCESS )
{
for ( PatternTokenList::const_iterator iter = pattern.begin(); iter != pattern.end(); iter++ )
{
( * iter )->format( s, exploded, p );
}
}
}
void SimpleDateFormat::setTimeZone( const TimeZonePtr & zone )
{
timeZone = zone;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/classregistration.h>
#include <log4cxx/helpers/class.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
ClassRegistration::ClassRegistration(ClassAccessor accessor) {
Class::registerClass((*accessor)());
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/fileappender.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/helpers/synchronized.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/helpers/fileoutputstream.h>
#include <log4cxx/helpers/outputstreamwriter.h>
#include <log4cxx/helpers/bufferedwriter.h>
#include <log4cxx/helpers/bytebuffer.h>
#include <log4cxx/helpers/synchronized.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
IMPLEMENT_LOG4CXX_OBJECT(FileAppender)
FileAppender::FileAppender() {
synchronized sync(mutex);
fileAppend = true;
bufferedIO = false;
bufferSize = 8 * 1024;
}
FileAppender::FileAppender(const LayoutPtr& layout1, const LogString& fileName1,
bool append1, bool bufferedIO1, int bufferSize1)
: WriterAppender(layout1) {
{
synchronized sync(mutex);
fileAppend = append1;
fileName = fileName1;
bufferedIO = bufferedIO1;
bufferSize = bufferSize1;
}
Pool p;
activateOptions(p);
}
FileAppender::FileAppender(const LayoutPtr& layout1, const LogString& fileName1,
bool append1)
: WriterAppender(layout1) {
{
synchronized sync(mutex);
fileAppend = append1;
fileName = fileName1;
bufferedIO = false;
bufferSize = 8 * 1024;
}
Pool p;
activateOptions(p);
}
FileAppender::FileAppender(const LayoutPtr& layout1, const LogString& fileName1)
: WriterAppender(layout1) {
{
synchronized sync(mutex);
fileAppend = true;
fileName = fileName1;
bufferedIO = false;
bufferSize = 8 * 1024;
}
Pool p;
activateOptions(p);
}
FileAppender::~FileAppender()
{
finalize();
}
void FileAppender::setAppend(bool fileAppend1) {
synchronized sync(mutex);
this->fileAppend = fileAppend1;
}
void FileAppender::setFile(const LogString& file)
{
synchronized sync(mutex);
fileName = file;
}
void FileAppender::setBufferedIO(bool bufferedIO1)
{
synchronized sync(mutex);
this->bufferedIO = bufferedIO1;
if(bufferedIO1)
{
setImmediateFlush(false);
}
}
void FileAppender::setOption(const LogString& option,
const LogString& value)
{
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("FILE"), LOG4CXX_STR("file"))
|| StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("FILENAME"), LOG4CXX_STR("filename")))
{
synchronized sync(mutex);
fileName = stripDuplicateBackslashes(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("APPEND"), LOG4CXX_STR("append")))
{
synchronized sync(mutex);
fileAppend = OptionConverter::toBoolean(value, true);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFEREDIO"), LOG4CXX_STR("bufferedio")))
{
synchronized sync(mutex);
bufferedIO = OptionConverter::toBoolean(value, true);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("IMMEDIATEFLUSH"), LOG4CXX_STR("immediateflush")))
{
synchronized sync(mutex);
bufferedIO = !OptionConverter::toBoolean(value, false);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFERSIZE"), LOG4CXX_STR("buffersize")))
{
synchronized sync(mutex);
bufferSize = OptionConverter::toFileSize(value, 8*1024);
}
else
{
WriterAppender::setOption(option, value);
}
}
void FileAppender::activateOptions(Pool& p)
{
synchronized sync(mutex);
int errors = 0;
if (!fileName.empty()) {
try {
setFile(fileName, fileAppend, bufferedIO, bufferSize, p);
} catch (IOException& e) {
errors++;
LogString msg(LOG4CXX_STR("setFile("));
msg.append(fileName);
msg.append(1, (logchar) 0x2C /* ',' */);
StringHelper::toString(fileAppend, msg);
msg.append(LOG4CXX_STR(") call failed."));
LogLog::error(msg, e);
}
} else {
errors++;
LogLog::error(LogString(LOG4CXX_STR("File option not set for appender ["))
+ name + LOG4CXX_STR("]."));
LogLog::warn(LOG4CXX_STR("Are you using FileAppender instead of ConsoleAppender?"));
}
if(errors == 0) {
WriterAppender::activateOptions(p);
}
}
/**
* Replaces double backslashes (except the leading doubles of UNC's)
* with single backslashes for compatibility with existing path
* specifications that were working around use of
* OptionConverter::convertSpecialChars in XML configuration files.
*
* @param src source string
* @return modified string
*
*
*/
LogString FileAppender::stripDuplicateBackslashes(const LogString& src) {
logchar backslash = 0x5C; // '\\'
LogString::size_type i = src.find_last_of(backslash);
if (i != LogString::npos) {
LogString tmp(src);
for(;
i != LogString::npos && i > 0;
i = tmp.find_last_of(backslash, i - 1)) {
//
// if the preceding character is a slash then
// remove the preceding character
// and continue processing
if (tmp[i - 1] == backslash) {
tmp.erase(i, 1);
i--;
if (i == 0) break;
} else {
//
// if there an odd number of slashes
// the string wasn't trying to work around
// OptionConverter::convertSpecialChars
return src;
}
}
return tmp;
}
return src;
}
/**
<p>Sets and <i>opens</i> the file where the log output will
go. The specified file must be writable.
<p>If there was already an opened file, then the previous file
is closed first.
<p><b>Do not use this method directly. To configure a FileAppender
or one of its subclasses, set its properties one by one and then
call activateOptions.</b>
@param filename The path to the log file.
@param append If true will append to fileName. Otherwise will
truncate fileName.
@param bufferedIO
@param bufferSize
@throws IOException
*/
void FileAppender::setFile(
const LogString& filename,
bool append1,
bool bufferedIO1,
size_t bufferSize1,
Pool& p) {
synchronized sync(mutex);
// It does not make sense to have immediate flush and bufferedIO.
if (bufferedIO1) {
setImmediateFlush(false);
}
closeWriter();
bool writeBOM = false;
if(StringHelper::equalsIgnoreCase(getEncoding(),
LOG4CXX_STR("utf-16"), LOG4CXX_STR("UTF-16"))) {
//
// don't want to write a byte order mark if the file exists
//
if (append1) {
File outFile;
outFile.setPath(filename);
writeBOM = !outFile.exists(p);
} else {
writeBOM = true;
}
}
OutputStreamPtr outStream;
try {
outStream = new FileOutputStream(filename, append1);
} catch(IOException& ex) {
LogString parentName = File().setPath(filename).getParent(p);
if (!parentName.empty()) {
File parentDir;
parentDir.setPath(parentName);
if(!parentDir.exists(p) && parentDir.mkdirs(p)) {
outStream = new FileOutputStream(filename, append1);
} else {
throw ex;
}
} else {
throw ex;
}
}
//
// if a new file and UTF-16, then write a BOM
//
if (writeBOM) {
char bom[] = { (char) 0xFE, (char) 0xFF };
ByteBuffer buf(bom, 2);
outStream->write(buf, p);
}
WriterPtr newWriter(createWriter(outStream));
if (bufferedIO1) {
newWriter = new BufferedWriter(newWriter, bufferSize1);
}
setWriter(newWriter);
this->fileAppend = append1;
this->bufferedIO = bufferedIO1;
this->fileName = filename;
this->bufferSize = bufferSize1;
writeHeader(p);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/inputstreamreader.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/helpers/bytebuffer.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(InputStreamReader)
InputStreamReader::InputStreamReader(const InputStreamPtr& in1)
: in(in1), dec(CharsetDecoder::getDefaultDecoder()) {
if (in1 == 0) {
throw NullPointerException(LOG4CXX_STR("in parameter may not be null."));
}
}
InputStreamReader::InputStreamReader(const InputStreamPtr& in1, const CharsetDecoderPtr &dec1)
: in(in1), dec(dec1) {
if (in1 == 0) {
throw NullPointerException(LOG4CXX_STR("in parameter may not be null."));
}
if (dec1 == 0) {
throw NullPointerException(LOG4CXX_STR("dec parameter may not be null."));
}
}
InputStreamReader::~InputStreamReader() {
}
void InputStreamReader::close(Pool& ) {
in->close();
}
LogString InputStreamReader::read(Pool& p) {
const size_t BUFSIZE = 4096;
ByteBuffer buf(p.pstralloc(BUFSIZE), BUFSIZE);
LogString output;
// read whole file
while(in->read(buf) >= 0) {
buf.flip();
log4cxx_status_t stat = dec->decode(buf, output);
if (stat != 0) {
throw IOException(stat);
}
if (buf.remaining() > 0) {
memmove(buf.data(), buf.current(), buf.remaining());
buf.limit(buf.remaining());
} else {
buf.clear();
}
}
return output;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/pattern/patternconverter.h>
#include <log4cxx/helpers/transcoder.h>
using namespace log4cxx;
using namespace log4cxx::pattern;
IMPLEMENT_LOG4CXX_OBJECT(PatternConverter)
PatternConverter::PatternConverter(
const LogString& name1, const LogString& style1) :
name(name1), style(style1) {
}
PatternConverter::~PatternConverter() {
}
LogString PatternConverter::getName() const {
return name;
}
LogString PatternConverter::getStyleClass(const log4cxx::helpers::ObjectPtr& /* e */) const {
return style;
}
void PatternConverter::append(LogString& toAppendTo, const std::string& src) {
LOG4CXX_DECODE_CHAR(decoded, src);
toAppendTo.append(decoded);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/ndc.h>
#include <log4cxx/level.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/system.h>
#include <log4cxx/helpers/socket.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/helpers/aprinitializer.h>
#include <log4cxx/helpers/threadspecificdata.h>
#include <log4cxx/helpers/transcoder.h>
#include <apr_time.h>
#include <apr_portable.h>
#include <apr_strings.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/objectoutputstream.h>
#include <log4cxx/helpers/bytebuffer.h>
#include <log4cxx/logger.h>
#include <log4cxx/private/log4cxx_private.h>
using namespace log4cxx;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(LoggingEvent)
//
// Accessor for start time.
//
log4cxx_time_t LoggingEvent::getStartTime() {
return log4cxx::helpers::APRInitializer::initialize();
}
LoggingEvent::LoggingEvent() :
ndc(0),
mdcCopy(0),
properties(0),
ndcLookupRequired(true),
mdcCopyLookupRequired(true),
timeStamp(0),
locationInfo() {
}
LoggingEvent::LoggingEvent(
const LogString& logger1, const LevelPtr& level1,
const LogString& message1, const LocationInfo& locationInfo1) :
logger(logger1),
level(level1),
ndc(0),
mdcCopy(0),
properties(0),
ndcLookupRequired(true),
mdcCopyLookupRequired(true),
message(message1),
timeStamp(apr_time_now()),
locationInfo(locationInfo1),
threadName(getCurrentThreadName()) {
}
LoggingEvent::~LoggingEvent()
{
delete ndc;
delete mdcCopy;
delete properties;
}
bool LoggingEvent::getNDC(LogString& dest) const
{
if(ndcLookupRequired)
{
ndcLookupRequired = false;
LogString val;
if(NDC::get(val)) {
ndc = new LogString(val);
}
}
if (ndc) {
dest.append(*ndc);
return true;
}
return false;
}
bool LoggingEvent::getMDC(const LogString& key, LogString& dest) const
{
// Note the mdcCopy is used if it exists. Otherwise we use the MDC
// that is associated with the thread.
if (mdcCopy != 0 && !mdcCopy->empty())
{
MDC::Map::const_iterator it = mdcCopy->find(key);
if (it != mdcCopy->end())
{
if (!it->second.empty())
{
dest.append(it->second);
return true;
}
}
}
return MDC::get(key, dest);
}
LoggingEvent::KeySet LoggingEvent::getMDCKeySet() const
{
LoggingEvent::KeySet set;
if (mdcCopy != 0 && !mdcCopy->empty())
{
MDC::Map::const_iterator it;
for (it = mdcCopy->begin(); it != mdcCopy->end(); it++)
{
set.push_back(it->first);
}
}
else
{
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
MDC::Map& m = data->getMap();
for(MDC::Map::const_iterator it = m.begin(); it != m.end(); it++) {
set.push_back(it->first);
}
}
}
return set;
}
void LoggingEvent::getMDCCopy() const
{
if(mdcCopyLookupRequired)
{
mdcCopyLookupRequired = false;
// the clone call is required for asynchronous logging.
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
mdcCopy = new MDC::Map(data->getMap());
} else {
mdcCopy = new MDC::Map();
}
}
}
bool LoggingEvent::getProperty(const LogString& key, LogString& dest) const
{
if (properties == 0)
{
return false;
}
std::map<LogString, LogString>::const_iterator it = properties->find(key);
if (it != properties->end())
{
dest.append(it->second);
return true;
}
return false;
}
LoggingEvent::KeySet LoggingEvent::getPropertyKeySet() const
{
LoggingEvent::KeySet set;
if (properties != 0)
{
std::map<LogString, LogString>::const_iterator it;
for (it = properties->begin(); it != properties->end(); it++)
{
set.push_back(it->first);
}
}
return set;
}
const LogString LoggingEvent::getCurrentThreadName() {
#if APR_HAS_THREADS
#if defined(_WIN32)
char result[20];
DWORD threadId = GetCurrentThreadId();
apr_snprintf(result, sizeof(result), LOG4CXX_WIN32_THREAD_FMTSPEC, threadId);
#else
// apr_os_thread_t encoded in HEX takes needs as many characters
// as two times the size of the type, plus an additional null byte.
char result[sizeof(apr_os_thread_t) * 3 + 10];
apr_os_thread_t threadId = apr_os_thread_current();
apr_snprintf(result, sizeof(result), LOG4CXX_APR_THREAD_FMTSPEC, (void*) &threadId);
#endif
LOG4CXX_DECODE_CHAR(str, (const char*) result);
return str;
#else
return LOG4CXX_STR("0x00000000");
#endif
}
void LoggingEvent::setProperty(const LogString& key, const LogString& value)
{
if (properties == 0)
{
properties = new std::map<LogString, LogString>;
}
(*properties)[key] = value;
}
void LoggingEvent::writeProlog(ObjectOutputStream& os, Pool& p) {
char classDesc[] = {
0x72, 0x00, 0x21,
0x6F, 0x72, 0x67, 0x2E, 0x61, 0x70, 0x61, 0x63,
0x68, 0x65, 0x2E, 0x6C, 0x6F, 0x67, 0x34, 0x6A,
0x2E, 0x73, 0x70, 0x69, 0x2E, 0x4C, 0x6F, 0x67,
0x67, 0x69, 0x6E, 0x67, 0x45, 0x76, 0x65, 0x6E,
0x74, 0xF3, 0xF2, 0xB9, 0x23, 0x74, 0x0B, 0xB5,
0x3F, 0x03, 0x00, 0x0A, 0x5A, 0x00, 0x15, 0x6D,
0x64, 0x63, 0x43, 0x6F, 0x70, 0x79, 0x4C, 0x6F,
0x6F, 0x6B, 0x75, 0x70, 0x52, 0x65, 0x71, 0x75,
0x69, 0x72, 0x65, 0x64, 0x5A, 0x00, 0x11, 0x6E,
0x64, 0x63, 0x4C, 0x6F, 0x6F, 0x6B, 0x75, 0x70,
0x52, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64,
0x4A, 0x00, 0x09, 0x74, 0x69, 0x6D, 0x65, 0x53,
0x74, 0x61, 0x6D, 0x70, 0x4C, 0x00, 0x0C, 0x63,
0x61, 0x74, 0x65, 0x67, 0x6F, 0x72, 0x79, 0x4E,
0x61, 0x6D, 0x65, 0x74, 0x00, 0x12, 0x4C, 0x6A,
0x61, 0x76, 0x61, 0x2F, 0x6C, 0x61, 0x6E, 0x67,
0x2F, 0x53, 0x74, 0x72, 0x69, 0x6E, 0x67, 0x3B,
0x4C, 0x00, 0x0C, 0x6C, 0x6F, 0x63, 0x61, 0x74,
0x69, 0x6F, 0x6E, 0x49, 0x6E, 0x66, 0x6F, 0x74,
0x00, 0x23, 0x4C, 0x6F, 0x72, 0x67, 0x2F, 0x61,
0x70, 0x61, 0x63, 0x68, 0x65, 0x2F, 0x6C, 0x6F,
0x67, 0x34, 0x6A, 0x2F, 0x73, 0x70, 0x69, 0x2F,
0x4C, 0x6F, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E,
0x49, 0x6E, 0x66, 0x6F, 0x3B, 0x4C, 0x00, 0x07,
0x6D, 0x64, 0x63, 0x43, 0x6F, 0x70, 0x79, 0x74,
0x00, 0x15, 0x4C, 0x6A, 0x61, 0x76, 0x61, 0x2F,
0x75, 0x74, 0x69, 0x6C, 0x2F, 0x48, 0x61, 0x73,
0x68, 0x74, 0x61, 0x62, 0x6C, 0x65, 0x3B, 0x4C,
0x00, 0x03, 0x6E, 0x64, 0x63,
0x74, 0x00, 0x12, 0x4C, 0x6A,
0x61, 0x76, 0x61, 0x2F, 0x6C, 0x61, 0x6E, 0x67,
0x2F, 0x53, 0x74, 0x72, 0x69, 0x6E, 0x67, 0x3B,
0x4C, 0x00, 0x0F, 0x72, 0x65, 0x6E,
0x64, 0x65, 0x72, 0x65, 0x64, 0x4D, 0x65, 0x73,
0x73, 0x61, 0x67, 0x65,
0x74, 0x00, 0x12, 0x4C, 0x6A,
0x61, 0x76, 0x61, 0x2F, 0x6C, 0x61, 0x6E, 0x67,
0x2F, 0x53, 0x74, 0x72, 0x69, 0x6E, 0x67, 0x3B,
0x4C, 0x00, 0x0A, 0x74, 0x68, 0x72, 0x65,
0x61, 0x64, 0x4E, 0x61, 0x6D, 0x65,
0x74, 0x00, 0x12, 0x4C, 0x6A,
0x61, 0x76, 0x61, 0x2F, 0x6C, 0x61, 0x6E, 0x67,
0x2F, 0x53, 0x74, 0x72, 0x69, 0x6E, 0x67, 0x3B,
0x4C, 0x00, 0x0D, 0x74, 0x68,
0x72, 0x6F, 0x77, 0x61, 0x62, 0x6C, 0x65, 0x49,
0x6E, 0x66, 0x6F, 0x74, 0x00, 0x2B, 0x4C, 0x6F,
0x72, 0x67, 0x2F, 0x61, 0x70, 0x61, 0x63, 0x68,
0x65, 0x2F, 0x6C, 0x6F, 0x67, 0x34, 0x6A, 0x2F,
0x73, 0x70, 0x69, 0x2F, 0x54, 0x68, 0x72, 0x6F,
0x77, 0x61, 0x62, 0x6C, 0x65, 0x49, 0x6E, 0x66,
0x6F, 0x72, 0x6D, 0x61, 0x74, 0x69, 0x6F, 0x6E,
0x3B, 0x78, 0x70 };
os.writeProlog("org.apache.log4j.spi.LoggingEvent",
8, classDesc, sizeof(classDesc), p);
}
void LoggingEvent::write(helpers::ObjectOutputStream& os, Pool& p) const {
writeProlog(os, p);
// mdc and ndc lookup required should always be false
char lookupsRequired[] = { 0, 0 };
os.writeBytes(lookupsRequired, sizeof(lookupsRequired), p);
os.writeLong(timeStamp/1000, p);
os.writeObject(logger, p);
locationInfo.write(os, p);
if (mdcCopy == 0 || mdcCopy->size() == 0) {
os.writeNull(p);
} else {
os.writeObject(*mdcCopy, p);
}
if (ndc == 0) {
os.writeNull(p);
} else {
os.writeObject(*ndc, p);
}
os.writeObject(message, p);
os.writeObject(threadName, p);
// throwable
os.writeNull(p);
os.writeByte(ObjectOutputStream::TC_BLOCKDATA, p);
os.writeByte(0x04, p);
os.writeInt(level->toInt(), p);
os.writeNull(p);
os.writeByte(ObjectOutputStream::TC_ENDBLOCKDATA, p);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define __STDC_CONSTANT_MACROS
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/relativetimedateformat.h>
#include <log4cxx/spi/loggingevent.h>
#include <apr.h>
#include <apr_time.h>
#include <log4cxx/helpers/stringhelper.h>
log4cxx::helpers::RelativeTimeDateFormat::RelativeTimeDateFormat()
: DateFormat(), startTime(log4cxx::spi::LoggingEvent::getStartTime())
{
}
void log4cxx::helpers::RelativeTimeDateFormat::format(
LogString &s,
log4cxx_time_t date,
Pool& p) const {
log4cxx_int64_t interval = (date - startTime) / APR_INT64_C(1000);
StringHelper::toString(interval, p, s);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/pattern/lineseparatorpatternconverter.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/spi/location/locationinfo.h>
using namespace log4cxx;
using namespace log4cxx::pattern;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(LineSeparatorPatternConverter)
LineSeparatorPatternConverter::LineSeparatorPatternConverter() :
LoggingEventPatternConverter(LOG4CXX_STR("Line Sep"),
LOG4CXX_STR("lineSep")) {
}
PatternConverterPtr LineSeparatorPatternConverter::newInstance(
const std::vector<LogString>& /* options */) {
static PatternConverterPtr instance(new LineSeparatorPatternConverter());
return instance;
}
void LineSeparatorPatternConverter::format(
const LoggingEventPtr& /* event */,
LogString& toAppendTo,
Pool& /* p */) const {
toAppendTo.append(LOG4CXX_EOL);
}
void LineSeparatorPatternConverter::format(
const ObjectPtr& /* event */,
LogString& toAppendTo,
Pool& /* p */) const {
toAppendTo.append(LOG4CXX_EOL);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/outputstream.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(OutputStream)
OutputStream::OutputStream() {
}
OutputStream::~OutputStream() {
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/spi/loggerfactory.h>
#include <log4cxx/spi/loggerrepository.h>
#include <log4cxx/appenderskeleton.h>
#include <log4cxx/helpers/optionconverter.h>
#include <algorithm>
#include <ctype.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/exception.h>
#include <stdlib.h>
#include <log4cxx/helpers/properties.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/level.h>
#include <log4cxx/helpers/object.h>
#include <log4cxx/helpers/class.h>
#include <log4cxx/helpers/loader.h>
#include <log4cxx/helpers/system.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/file.h>
#include <log4cxx/xml/domconfigurator.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
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;
}
bool OptionConverter::toBoolean(const LogString& value, bool dEfault)
{
if (value.length() >= 4) {
if (StringHelper::equalsIgnoreCase(value.substr(0,4),
LOG4CXX_STR("TRUE"), LOG4CXX_STR("true"))) {
return true;
}
}
if (dEfault && value.length() >= 5) {
if (StringHelper::equalsIgnoreCase(value.substr(0,5),
LOG4CXX_STR("FALSE"), LOG4CXX_STR("false"))) {
return false;
}
}
return dEfault;
}
int OptionConverter::toInt(const LogString& value, int dEfault)
{
LogString trimmed(StringHelper::trim(value));
if (trimmed.empty())
{
return dEfault;
}
LOG4CXX_ENCODE_CHAR(cvalue, trimmed);
return (int) atol(cvalue.c_str());
}
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);
}
LogString OptionConverter::findAndSubst(const LogString& key, Properties& props)
{
LogString value(props.getProperty(key));
if(value.empty())
return value;
try
{
return substVars(value, props);
}
catch(IllegalArgumentException& e)
{
LogLog::error(((LogString) LOG4CXX_STR("Bad option value ["))
+ value + LOG4CXX_STR("]."), e);
return value;
}
}
LogString OptionConverter::substVars(const LogString& val, Properties& props)
{
LogString sbuf;
const logchar delimStartArray[] = { 0x24, 0x7B, 0 };
const LogString delimStart(delimStartArray);
const logchar delimStop = 0x7D; // '}';
const size_t DELIM_START_LEN = 2;
const size_t DELIM_STOP_LEN = 1;
int i = 0;
int j, k;
while(true)
{
j = val.find(delimStart, i);
if(j == -1)
{
// no more variables
if(i==0)
{ // this is a simple string
return val;
}
else
{ // add the tail string which contails no variables and return the result.
sbuf.append(val.substr(i, val.length() - i));
return sbuf;
}
}
else
{
sbuf.append(val.substr(i, j - i));
k = val.find(delimStop, j);
if(k == -1)
{
LogString msg(1, (logchar) 0x22 /* '\"' */);
msg.append(val);
msg.append(LOG4CXX_STR("\" has no closing brace. Opening brace at position "));
Pool p;
StringHelper::toString(j, p, msg);
msg.append(1, (logchar) 0x2E /* '.' */);
throw IllegalArgumentException(msg);
}
else
{
j += DELIM_START_LEN;
LogString key = val.substr(j, k - j);
// first try in System properties
LogString replacement(getSystemProperty(key, LogString()));
// then try props parameter
if(replacement.empty())
{
replacement = props.getProperty(key);
}
if(!replacement.empty())
{
// Do variable substitution on the replacement string
// such that we can solve "Hello ${x2}" as "Hello p1"
// the where the properties are
// x1=p1
// x2=${x1}
LogString recursiveReplacement = substVars(replacement, props);
sbuf.append(recursiveReplacement);
}
i = k + DELIM_STOP_LEN;
}
}
}
}
LogString OptionConverter::getSystemProperty(const LogString& key, const LogString& def)
{
if (!key.empty())
{
LogString value(System::getProperty(key));
if (!value.empty())
{
return value;
}
}
return def;
}
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;
}
ObjectPtr OptionConverter::instantiateByKey(Properties& props, const LogString& key,
const Class& superClass, const ObjectPtr& defaultValue)
{
// Get the value of the property in string form
LogString className(findAndSubst(key, props));
if(className.empty())
{
LogLog::error(
((LogString) LOG4CXX_STR("Could not find value for key ")) + key);
return defaultValue;
}
// Trim className to avoid trailing spaces that cause problems.
return OptionConverter::instantiateByClassName(
StringHelper::trim(className), superClass, defaultValue);
}
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 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);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/helpers/socket.h>
#include <log4cxx/helpers/bytebuffer.h>
#include <log4cxx/helpers/transcoder.h>
#include "apr_network_io.h"
#include "apr_signal.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(Socket)
/** Creates a stream socket and connects it to the specified port
number at the specified IP address.
*/
Socket::Socket(InetAddressPtr& address, int port) : pool(), socket(0), address(address), port(port)
{
apr_status_t status =
apr_socket_create(&socket, APR_INET, SOCK_STREAM,
APR_PROTO_TCP, pool.getAPRPool());
if (status != APR_SUCCESS) {
throw SocketException(status);
}
LOG4CXX_ENCODE_CHAR(host, address->getHostAddress());
// create socket address (including port)
apr_sockaddr_t *client_addr;
status =
apr_sockaddr_info_get(&client_addr, host.c_str(), APR_INET,
port, 0, pool.getAPRPool());
if (status != APR_SUCCESS) {
throw ConnectException(status);
}
// connect the socket
status = apr_socket_connect(socket, client_addr);
if (status != APR_SUCCESS) {
throw ConnectException(status);
}
}
Socket::Socket(apr_socket_t* socket, apr_pool_t* pool) :
pool(pool, true), socket(socket) {
apr_sockaddr_t* sa;
apr_status_t status = apr_socket_addr_get(&sa, APR_REMOTE, socket);
if (status == APR_SUCCESS) {
port = sa->port;
LogString remotename;
LogString remoteip;
if (sa->hostname != NULL) {
Transcoder::decode(sa->hostname, remotename);
}
char* buf = 0;
status = apr_sockaddr_ip_get(&buf, sa);
if (status == APR_SUCCESS) {
Transcoder::decode(buf, remoteip);
}
address = new InetAddress(remotename, remoteip);
}
}
Socket::~Socket() {
}
size_t Socket::write(ByteBuffer& buf) {
if (socket == 0) {
throw ClosedChannelException();
}
int totalWritten = 0;
while(buf.remaining() > 0) {
apr_size_t written = buf.remaining();
// while writing to the socket, we need to ignore the SIGPIPE
// signal. Otherwise, when the client has closed the connection,
// the send() function would not return an error but call the
// SIGPIPE handler.
#if APR_HAVE_SIGACTION
apr_sigfunc_t* old = apr_signal(SIGPIPE, SIG_IGN);
apr_status_t status = apr_socket_send(socket, buf.current(), &written);
apr_signal(SIGPIPE, old);
#else
apr_status_t status = apr_socket_send(socket, buf.current(), &written);
#endif
buf.position(buf.position() + written);
totalWritten += written;
if (status != APR_SUCCESS) {
throw SocketException(status);
}
}
return totalWritten;
}
void Socket::close() {
if (socket != 0) {
apr_status_t status = apr_socket_close(socket);
if (status != APR_SUCCESS) {
throw SocketException(status);
}
socket = 0;
}
}
InetAddressPtr Socket::getInetAddress() const {
return address;
}
int Socket::getPort() const {
return port;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/defaultconfigurator.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/spi/loggerrepository.h>
#include <log4cxx/file.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/optionconverter.h>
using namespace log4cxx;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
void DefaultConfigurator::configure(LoggerRepository* repository)
{
repository->setConfigured(true);
const LogString configuratorClassName(getConfiguratorClass());
LogString configurationOptionStr(getConfigurationFileName());
Pool pool;
File configuration;
if (configurationOptionStr.empty())
{
const char* names[] = { "log4cxx.xml", "log4cxx.properties", "log4j.xml", "log4j.properties", 0 };
for (int i = 0; names[i] != 0; i++) {
File candidate(names[i]);
if (candidate.exists(pool)) {
configuration = candidate;
break;
}
}
} else {
configuration.setPath(configurationOptionStr);
}
if (configuration.exists(pool))
{
LogString msg(LOG4CXX_STR("Using configuration file ["));
msg += configuration.getPath();
msg += LOG4CXX_STR("] for automatic log4cxx configuration");
LogLog::debug(msg);
LoggerRepositoryPtr repo(repository);
OptionConverter::selectAndConfigure(
configuration,
configuratorClassName,
repo);
}
else
{
if (configurationOptionStr.empty()) {
LogLog::debug(LOG4CXX_STR("Could not find default configuration file."));
} else {
LogString msg(LOG4CXX_STR("Could not find configuration file: ["));
msg += configurationOptionStr;
msg += LOG4CXX_STR("].");
LogLog::debug(msg);
}
}
}
const LogString DefaultConfigurator::getConfiguratorClass() {
// Use automatic configration to configure the default hierarchy
const LogString log4jConfiguratorClassName(
OptionConverter::getSystemProperty(LOG4CXX_STR("log4j.configuratorClass"),LOG4CXX_STR("")));
const LogString configuratorClassName(
OptionConverter::getSystemProperty(LOG4CXX_STR("LOG4CXX_CONFIGURATOR_CLASS"),
log4jConfiguratorClassName));
return configuratorClassName;
}
const LogString DefaultConfigurator::getConfigurationFileName() {
static const LogString LOG4CXX_DEFAULT_CONFIGURATION_KEY(LOG4CXX_STR("LOG4CXX_CONFIGURATION"));
static const LogString LOG4J_DEFAULT_CONFIGURATION_KEY(LOG4CXX_STR("log4j.configuration"));
const LogString log4jConfigurationOptionStr(
OptionConverter::getSystemProperty(LOG4J_DEFAULT_CONFIGURATION_KEY, LOG4CXX_STR("")));
const LogString configurationOptionStr(
OptionConverter::getSystemProperty(LOG4CXX_DEFAULT_CONFIGURATION_KEY,
log4jConfigurationOptionStr));
return configurationOptionStr;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/pattern/threadpatternconverter.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/spi/location/locationinfo.h>
using namespace log4cxx;
using namespace log4cxx::pattern;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(ThreadPatternConverter)
ThreadPatternConverter::ThreadPatternConverter() :
LoggingEventPatternConverter(LOG4CXX_STR("Thread"),
LOG4CXX_STR("Thread")) {
}
PatternConverterPtr ThreadPatternConverter::newInstance(
const std::vector<LogString>& /* options */) {
static PatternConverterPtr def(new ThreadPatternConverter());
return def;
}
void ThreadPatternConverter::format(
const LoggingEventPtr& event,
LogString& toAppendTo,
Pool& /* p */) const {
toAppendTo.append(event->getThreadName());
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/ttcclayout.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/level.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/ndc.h>
using namespace log4cxx;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(TTCCLayout)
TTCCLayout::TTCCLayout()
: DateLayout(LOG4CXX_STR("RELATIVE")), threadPrinting(true), categoryPrefixing(true),
contextPrinting(true), filePrinting(false)
{
Pool pool;
activateOptions(pool);
}
TTCCLayout::TTCCLayout(const LogString& dateFormatType)
: DateLayout(dateFormatType), threadPrinting(true), categoryPrefixing(true),
contextPrinting(true), filePrinting(false)
{
Pool pool;
activateOptions(pool);
}
void TTCCLayout::format(LogString& output,
const spi::LoggingEventPtr& event,
Pool& p) const
{
formatDate(output, event, p);
if(threadPrinting)
{
output.append(1, (logchar) 0x5B /* '[' */);
output.append(event->getThreadName());
output.append(1, (logchar) 0x5D /* ']' */);
output.append(1, (logchar) 0x20 /* ' ' */);
}
output.append(event->getLevel()->toString());
output.append(1, (logchar) 0x20 /* ' ' */);
if(categoryPrefixing)
{
output.append(event->getLoggerName());
output.append(1, (logchar) 0x20 /* ' ' */);
}
if(contextPrinting && event->getNDC(output)) {
output.append(1, (logchar) 0x20 /* ' ' */);
}
output.append(1, (logchar) 0x2D /* '-' */);
output.append(1, (logchar) 0x20 /* ' ' */);
output.append(event->getRenderedMessage());
output.append(LOG4CXX_EOL);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/rolling/fixedwindowrollingpolicy.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/helpers/integer.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/rolling/rolloverdescription.h>
#include <log4cxx/rolling/filerenameaction.h>
#include <log4cxx/rolling/gzcompressaction.h>
#include <log4cxx/rolling/zipcompressaction.h>
#include <log4cxx/pattern/integerpatternconverter.h>
using namespace log4cxx;
using namespace log4cxx::rolling;
using namespace log4cxx::helpers;
using namespace log4cxx::pattern;
IMPLEMENT_LOG4CXX_OBJECT(FixedWindowRollingPolicy)
FixedWindowRollingPolicy::FixedWindowRollingPolicy() :
minIndex(1), maxIndex(7) {
}
void FixedWindowRollingPolicy::setMaxIndex(int maxIndex1) {
this->maxIndex = maxIndex1;
}
void FixedWindowRollingPolicy::setMinIndex(int minIndex1) {
this->minIndex = minIndex1;
}
void FixedWindowRollingPolicy::setOption(const LogString& option,
const LogString& value) {
if (StringHelper::equalsIgnoreCase(option,
LOG4CXX_STR("MININDEX"),
LOG4CXX_STR("minindex"))) {
minIndex = OptionConverter::toInt(value, 1);
} else if (StringHelper::equalsIgnoreCase(option,
LOG4CXX_STR("MAXINDEX"),
LOG4CXX_STR("maxindex"))) {
maxIndex = OptionConverter::toInt(value, 7);
} else {
RollingPolicyBase::setOption(option, value);
}
}
/**
* {@inheritDoc}
*/
void FixedWindowRollingPolicy::activateOptions(Pool& p) {
RollingPolicyBase::activateOptions(p);
if (maxIndex < minIndex) {
LogLog::warn(
LOG4CXX_STR("MaxIndex cannot be smaller than MinIndex."));
maxIndex = minIndex;
}
if ((maxIndex - minIndex) > MAX_WINDOW_SIZE) {
LogLog::warn(LOG4CXX_STR("Large window sizes are not allowed."));
maxIndex = minIndex + MAX_WINDOW_SIZE;
}
PatternConverterPtr itc = getIntegerPatternConverter();
if (itc == NULL) {
throw IllegalStateException();
}
}
/**
* {@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);
}
/**
* {@inheritDoc}
*/
RolloverDescriptionPtr FixedWindowRollingPolicy::rollover(
const LogString& currentFileName,
log4cxx::helpers::Pool& p) {
RolloverDescriptionPtr desc;
if (maxIndex >= 0) {
int purgeStart = minIndex;
if (!explicitActiveFile) {
purgeStart++;
}
if (!purge(purgeStart, maxIndex, p)) {
return desc;
}
LogString buf;
ObjectPtr obj(new Integer(purgeStart));
formatFileName(obj, buf, p);
LogString renameTo(buf);
LogString compressedName(renameTo);
ActionPtr compressAction ;
if (StringHelper::endsWith(renameTo, LOG4CXX_STR(".gz"))) {
renameTo.resize(renameTo.size() - 3);
compressAction =
new GZCompressAction(
File().setPath(renameTo), File().setPath(compressedName), true);
} else if (StringHelper::endsWith(renameTo, LOG4CXX_STR(".zip"))) {
renameTo.resize(renameTo.size() - 4);
compressAction =
new ZipCompressAction(
File().setPath(renameTo), File().setPath(compressedName), true);
}
FileRenameActionPtr renameAction =
new FileRenameAction(
File().setPath(currentFileName), File().setPath(renameTo), false);
desc = new RolloverDescription(
currentFileName, false, renameAction, compressAction);
}
return desc;
}
/**
* Get index of oldest log file to be retained.
* @return index of oldest log file.
*/
int FixedWindowRollingPolicy::getMaxIndex() const {
return maxIndex;
}
/**
* Get index of most recent log file.
* @return index of oldest log file.
*/
int FixedWindowRollingPolicy::getMinIndex() const {
return minIndex;
}
/**
* 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& ex) {
LogLog::warn(LOG4CXX_STR("Exception during purge in RollingFileAppender"));
return false;
}
}
return true;
}
#define RULES_PUT(spec, cls) \
specs.insert(PatternMap::value_type(LogString(LOG4CXX_STR(spec)), (PatternConstructor) cls ::newInstance))
log4cxx::pattern::PatternMap FixedWindowRollingPolicy::getFormatSpecifiers() const {
PatternMap specs;
RULES_PUT("i", IntegerPatternConverter);
RULES_PUT("index", IntegerPatternConverter);
return specs;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/condition.h>
#include <log4cxx/helpers/exception.h>
#include <apr_thread_cond.h>
#include <log4cxx/helpers/synchronized.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/helpers/thread.h>
using namespace log4cxx::helpers;
using namespace log4cxx;
Condition::Condition(Pool& p)
{
#if APR_HAS_THREADS
apr_status_t stat = apr_thread_cond_create(&condition, p.getAPRPool());
if (stat != APR_SUCCESS) {
throw RuntimeException(stat);
}
#endif
}
Condition::~Condition()
{
#if APR_HAS_THREADS
apr_thread_cond_destroy(condition);
#endif
}
log4cxx_status_t Condition::signalAll()
{
#if APR_HAS_THREADS
return apr_thread_cond_broadcast(condition);
#else
return APR_SUCCESS;
#endif
}
void Condition::await(Mutex& mutex)
{
#if APR_HAS_THREADS
if (Thread::interrupted()) {
throw InterruptedException();
}
apr_status_t stat = apr_thread_cond_wait(
condition,
mutex.getAPRMutex());
if (stat != APR_SUCCESS) {
throw InterruptedException(stat);
}
#endif
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/pattern/levelpatternconverter.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/spi/location/locationinfo.h>
#include <log4cxx/level.h>
using namespace log4cxx;
using namespace log4cxx::pattern;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(LevelPatternConverter)
LevelPatternConverter::LevelPatternConverter() :
LoggingEventPatternConverter(LOG4CXX_STR("Level"),
LOG4CXX_STR("level")) {
}
PatternConverterPtr LevelPatternConverter::newInstance(
const std::vector<LogString>& /* options */) {
static PatternConverterPtr def(new LevelPatternConverter());
return def;
}
void LevelPatternConverter::format(
const LoggingEventPtr& event,
LogString& toAppendTo,
log4cxx::helpers::Pool& /* p */) const {
toAppendTo.append(event->getLevel()->toString());
}
/**
* {@inheritDoc}
*/
LogString LevelPatternConverter::getStyleClass(const ObjectPtr& obj) const {
LoggingEventPtr e(obj);
if (e != NULL) {
int lint = e->getLevel()->toInt();
switch (lint) {
case Level::TRACE_INT:
return LOG4CXX_STR("level trace");
case Level::DEBUG_INT:
return LOG4CXX_STR("level debug");
case Level::INFO_INT:
return LOG4CXX_STR("level info");
case Level::WARN_INT:
return LOG4CXX_STR("level warn");
case Level::ERROR_INT:
return LOG4CXX_STR("level error");
case Level::FATAL_INT:
return LOG4CXX_STR("level fatal");
default:
return LogString(LOG4CXX_STR("level ")) + e->getLevel()->toString();
}
}
return LOG4CXX_STR("level");
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/rolling/rollingpolicybase.h>
#include <log4cxx/pattern/formattinginfo.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/pattern/patternparser.h>
#include <log4cxx/pattern/integerpatternconverter.h>
#include <log4cxx/pattern/datepatternconverter.h>
using namespace log4cxx;
using namespace log4cxx::rolling;
using namespace log4cxx::helpers;
using namespace log4cxx::pattern;
IMPLEMENT_LOG4CXX_OBJECT(RollingPolicyBase)
RollingPolicyBase::RollingPolicyBase() {
}
RollingPolicyBase::~RollingPolicyBase() {
}
void RollingPolicyBase::addRef() const {
ObjectImpl::addRef();
}
void RollingPolicyBase::releaseRef() const {
ObjectImpl::releaseRef();
}
void RollingPolicyBase::activateOptions(log4cxx::helpers::Pool& /* pool */) {
if (fileNamePatternStr.length() > 0) {
parseFileNamePattern();
} else {
LogString msg(LOG4CXX_STR("The FileNamePattern option must be set before using FixedWindowRollingPolicy."));
LogString ref1(LOG4CXX_STR("See also http://logging.apache.org/log4j/codes.html#tbr_fnp_not_set"));
LogLog::warn(msg);
LogLog::warn(ref1);
throw IllegalStateException();
}
}
void RollingPolicyBase::setOption(const LogString& option, const LogString& value) {
if (StringHelper::equalsIgnoreCase(option,
LOG4CXX_STR("FILENAMEPATTERN"),
LOG4CXX_STR("filenamepattern"))) {
fileNamePatternStr = value;
}
}
void RollingPolicyBase::setFileNamePattern(const LogString& fnp) {
fileNamePatternStr = fnp;
}
LogString RollingPolicyBase::getFileNamePattern() const {
return fileNamePatternStr;
}
/**
* Parse file name pattern.
*/
void RollingPolicyBase::parseFileNamePattern() {
patternConverters.erase(patternConverters.begin(), patternConverters.end());
patternFields.erase(patternFields.begin(), patternFields.end());
PatternParser::parse(fileNamePatternStr,
patternConverters,
patternFields,
getFormatSpecifiers());
}
/**
* Format file name.
*
* @param obj object to be evaluted in formatting, may not be null.
* @param buf string buffer to which formatted file name is appended, may not be null.
*/
void RollingPolicyBase::formatFileName(
ObjectPtr& obj,
LogString& toAppendTo,
Pool& pool) const {
std::vector<FormattingInfoPtr>::const_iterator formatterIter =
patternFields.begin();
for(std::vector<PatternConverterPtr>::const_iterator
converterIter = patternConverters.begin();
converterIter != patternConverters.end();
converterIter++, formatterIter++) {
int startField = toAppendTo.length();
(*converterIter)->format(obj, toAppendTo, pool);
(*formatterIter)->format(startField, toAppendTo);
}
}
PatternConverterPtr RollingPolicyBase::getIntegerPatternConverter() const {
for(std::vector<PatternConverterPtr>::const_iterator
converterIter = patternConverters.begin();
converterIter != patternConverters.end();
converterIter++) {
IntegerPatternConverterPtr intPattern(*converterIter);
if (intPattern != NULL) {
return *converterIter;
}
}
PatternConverterPtr noMatch;
return noMatch;
}
PatternConverterPtr RollingPolicyBase::getDatePatternConverter() const {
for(std::vector<PatternConverterPtr>::const_iterator
converterIter = patternConverters.begin();
converterIter != patternConverters.end();
converterIter++) {
DatePatternConverterPtr datePattern(*converterIter);
if (datePattern != NULL) {
return *converterIter;
}
}
PatternConverterPtr noMatch;
return noMatch;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/appenderattachableimpl.h>
#include <log4cxx/appender.h>
#include <log4cxx/spi/loggingevent.h>
#include <algorithm>
#include <log4cxx/helpers/pool.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
IMPLEMENT_LOG4CXX_OBJECT(AppenderAttachableImpl)
AppenderAttachableImpl::AppenderAttachableImpl(Pool& pool)
: appenderList(),
mutex(pool) {
}
void AppenderAttachableImpl::addRef() const {
ObjectImpl::addRef();
}
void AppenderAttachableImpl::releaseRef() const {
ObjectImpl::releaseRef();
}
void AppenderAttachableImpl::addAppender(const AppenderPtr& newAppender)
{
// Null values for newAppender parameter are strictly forbidden.
if(newAppender == 0)
{
return;
}
AppenderList::iterator it = std::find(
appenderList.begin(), appenderList.end(), newAppender);
if (it == appenderList.end())
{
appenderList.push_back(newAppender);
}
}
int AppenderAttachableImpl::appendLoopOnAppenders(
const spi::LoggingEventPtr& event,
Pool& p)
{
for (AppenderList::iterator it = appenderList.begin();
it != appenderList.end();
it++) {
(*it)->doAppend(event, p);
}
return appenderList.size();
}
AppenderList AppenderAttachableImpl::getAllAppenders() const
{
return appenderList;
}
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;
}
bool AppenderAttachableImpl::isAttached(const AppenderPtr& appender) const
{
if (appender == 0)
{
return false;
}
AppenderList::const_iterator it = std::find(
appenderList.begin(), appenderList.end(), appender);
return it != appenderList.end();
}
void AppenderAttachableImpl::removeAllAppenders()
{
AppenderList::iterator it, itEnd = appenderList.end();
AppenderPtr a;
for(it = appenderList.begin(); it != itEnd; it++)
{
a = *it;
a->close();
}
appenderList.clear();
}
void AppenderAttachableImpl::removeAppender(const AppenderPtr& appender)
{
if (appender == 0)
return;
AppenderList::iterator it = std::find(
appenderList.begin(), appenderList.end(), appender);
if (it != appenderList.end())
{
appenderList.erase(it);
}
}
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;
}
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/pool.h>
#include <apr_strings.h>
#include <log4cxx/helpers/exception.h>
#include <apr_pools.h>
#include <assert.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/helpers/aprinitializer.h>
using namespace log4cxx::helpers;
using namespace log4cxx;
Pool::Pool() : pool(0), release(true) {
apr_status_t stat = apr_pool_create(&pool, APRInitializer::getRootPool());
if (stat != APR_SUCCESS) {
throw PoolException(stat);
}
}
Pool::Pool(apr_pool_t* p, bool release1) : pool(p), release(release1) {
assert(p != NULL);
}
Pool::~Pool() {
if (release) {
apr_pool_destroy(pool);
}
}
apr_pool_t* Pool::getAPRPool() {
return pool;
}
apr_pool_t* Pool::create() {
apr_pool_t* child;
apr_status_t stat = apr_pool_create(&child, pool);
if (stat != APR_SUCCESS) {
throw PoolException(stat);
}
return child;
}
void* Pool::palloc(size_t size) {
return apr_palloc(pool, size);
}
char* Pool::pstralloc(size_t size) {
return (char*) palloc(size);
}
char* Pool::itoa(int n) {
return apr_itoa(pool, n);
}
char* Pool::pstrndup(const char* s, size_t len) {
return apr_pstrndup(pool, s, len);
}
char* Pool::pstrdup(const char* s) {
return apr_pstrdup(pool, s);
}
char* Pool::pstrdup(const std::string& s) {
return apr_pstrndup(pool, s.data(), s.length());
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/net/sockethubappender.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/serversocket.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/helpers/synchronized.h>
#include <apr_atomic.h>
#include <apr_thread_proc.h>
#include <log4cxx/helpers/objectoutputstream.h>
#include <log4cxx/helpers/socketoutputstream.h>
#include <log4cxx/helpers/exception.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::net;
using namespace log4cxx::spi;
#if APR_HAS_THREADS
IMPLEMENT_LOG4CXX_OBJECT(SocketHubAppender)
int SocketHubAppender::DEFAULT_PORT = 4560;
SocketHubAppender::~SocketHubAppender()
{
finalize();
}
SocketHubAppender::SocketHubAppender()
: port(DEFAULT_PORT), streams(), locationInfo(false), thread()
{
}
SocketHubAppender::SocketHubAppender(int port1)
: port(port1), streams(), locationInfo(false), thread()
{
startServer();
}
void SocketHubAppender::activateOptions(Pool& /* p */ )
{
startServer();
}
void SocketHubAppender::setOption(const LogString& option,
const LogString& value)
{
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("PORT"), LOG4CXX_STR("port")))
{
setPort(OptionConverter::toInt(value, DEFAULT_PORT));
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOCATIONINFO"), LOG4CXX_STR("locationinfo")))
{
setLocationInfo(OptionConverter::toBoolean(value, true));
}
else
{
AppenderSkeleton::setOption(option, value);
}
}
void SocketHubAppender::close()
{
{
synchronized sync(mutex);
if (closed) {
return;
}
closed = true;
}
LogLog::debug(LOG4CXX_STR("closing SocketHubAppender ") + getName());
//
// wait until the server thread completes
//
thread.join();
synchronized sync(mutex);
// close all of the connections
LogLog::debug(LOG4CXX_STR("closing client connections"));
for (std::vector<helpers::ObjectOutputStreamPtr>::iterator iter = streams.begin();
iter != streams.end();
iter++) {
if ( (*iter) != NULL) {
try {
(*iter)->close(pool);
} catch(SocketException& e) {
LogLog::error(LOG4CXX_STR("could not close socket: "), e);
}
}
}
streams.erase(streams.begin(), streams.end());
LogLog::debug(LOG4CXX_STR("SocketHubAppender ")
+ getName() + LOG4CXX_STR(" closed"));
}
void SocketHubAppender::append(const spi::LoggingEventPtr& event, Pool& p)
{
// if no open connections, exit now
if(streams.empty())
{
return;
}
LogString ndcVal;
event->getNDC(ndcVal);
event->getThreadName();
// Get a copy of this thread's MDC.
event->getMDCCopy();
// loop through the current set of open connections, appending the event to each
std::vector<ObjectOutputStreamPtr>::iterator it = streams.begin();
std::vector<ObjectOutputStreamPtr>::iterator itEnd = streams.end();
while(it != itEnd)
{
// list size changed unexpectedly? Just exit the append.
if (*it == 0)
{
break;
}
try
{
event->write(**it, p);
(*it)->flush(p);
it++;
}
catch(std::exception& e)
{
// there was an io exception so just drop the connection
it = streams.erase(it);
LogLog::debug(LOG4CXX_STR("dropped connection"), e);
}
}
}
void SocketHubAppender::startServer()
{
thread.run(monitor, this);
}
void* APR_THREAD_FUNC SocketHubAppender::monitor(apr_thread_t* /* thread */, void* data) {
SocketHubAppender* pThis = (SocketHubAppender*) data;
ServerSocket* serverSocket = 0;
try
{
serverSocket = new ServerSocket(pThis->port);
serverSocket->setSoTimeout(1000);
}
catch (SocketException& e)
{
LogLog::error(LOG4CXX_STR("exception setting timeout, shutting down server socket."), e);
delete serverSocket;
return NULL;
}
bool stopRunning = pThis->closed;
while (!stopRunning)
{
SocketPtr socket;
try
{
socket = serverSocket->accept();
}
catch (InterruptedIOException&)
{
// timeout occurred, so just loop
}
catch (SocketException& e)
{
LogLog::error(LOG4CXX_STR("exception accepting socket, shutting down server socket."), e);
stopRunning = true;
}
catch (IOException& e)
{
LogLog::error(LOG4CXX_STR("exception accepting socket."), e);
}
// if there was a socket accepted
if (socket != 0)
{
try
{
InetAddressPtr remoteAddress = socket->getInetAddress();
LogLog::debug(LOG4CXX_STR("accepting connection from ")
+ remoteAddress->getHostName()
+ LOG4CXX_STR(" (")
+ remoteAddress->getHostAddress()
+ LOG4CXX_STR(")"));
// add it to the oosList.
synchronized sync(pThis->mutex);
OutputStreamPtr os(new SocketOutputStream(socket));
Pool p;
ObjectOutputStreamPtr oos(new ObjectOutputStream(os, p));
pThis->streams.push_back(oos);
}
catch (IOException& e)
{
LogLog::error(LOG4CXX_STR("exception creating output stream on socket."), e);
}
}
stopRunning = (stopRunning || pThis->closed);
}
delete serverSocket;
return NULL;
}
#endif
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/rolling/rolloverdescription.h>
using namespace log4cxx;
using namespace log4cxx::rolling;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(RolloverDescription)
RolloverDescription::RolloverDescription() {
}
RolloverDescription::RolloverDescription(
const LogString& activeFileName1,
const bool append1,
const ActionPtr& synchronous1,
const ActionPtr& asynchronous1)
: activeFileName(activeFileName1),
append(append1),
synchronous(synchronous1),
asynchronous(asynchronous1) {
}
LogString RolloverDescription::getActiveFileName() const {
return activeFileName;
}
bool RolloverDescription::getAppend() const {
return append;
}
ActionPtr RolloverDescription::getSynchronous() const {
return synchronous;
}
/**
* Action to be completed after close of current active log file
* and before next rollover attempt, may be executed asynchronously.
*
* @return action, may be null.
*/
ActionPtr RolloverDescription::getAsynchronous() const {
return asynchronous;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/pattern/patternparser.h>
#include <log4cxx/pattern/literalpatternconverter.h>
#include <log4cxx/helpers/loglog.h>
using namespace log4cxx;
using namespace log4cxx::pattern;
using namespace log4cxx::helpers;
const logchar PatternParser::ESCAPE_CHAR = 0x25; // '%'
/**
* Private constructor.
*/
PatternParser::PatternParser() {
}
bool PatternParser::isUnicodeIdentifierStart(logchar ch) {
//
// greatly simplified version checks if
// character is USACII alpha or number
//
return (ch >= 0x41 /* 'A' */ && ch <= 0x5A /* 'Z' */) ||
(ch >= 0x61 /* 'a' */ && ch <= 0x7A /* 'z' */) ||
(ch >= 0x30 /* '0' */ && ch <= 0x39 /* '9' */);
}
bool PatternParser::isUnicodeIdentifierPart(logchar ch) {
//
// greatly simplified version checks if
// character is USACII alpha or number
//
return isUnicodeIdentifierStart(ch)
|| (ch == 0x5F /* '_' */);
}
int PatternParser::extractConverter(
logchar lastChar, const LogString& pattern,
LogString::size_type i, LogString& convBuf,
LogString& currentLiteral) {
if (!convBuf.empty()) {
convBuf.erase(convBuf.begin(), convBuf.end());
}
// When this method is called, lastChar points to the first character of the
// conversion word. For example:
// For "%hello" lastChar = 'h'
// For "%-5hello" lastChar = 'h'
//System.out.println("lastchar is "+lastChar);
if (!isUnicodeIdentifierStart(lastChar)) {
return i;
}
convBuf.append(1, lastChar);
while (
(i < pattern.length())
&& isUnicodeIdentifierPart(pattern[i])) {
convBuf.append(1, pattern[i]);
currentLiteral.append(1, pattern[i]);
//System.out.println("conv buffer is now ["+convBuf+"].");
i++;
}
return i;
}
int PatternParser::extractOptions(const LogString& pattern, LogString::size_type i,
std::vector<LogString>& options) {
while ((i < pattern.length()) && (pattern[i] == 0x7B /* '{' */)) {
int end = pattern.find(0x7D /* '}' */, i);
if (end == -1) {
break;
}
LogString r(pattern.substr(i + 1, end - i - 1));
options.push_back(r);
i = end + 1;
}
return i;
}
void PatternParser::parse(
const LogString& pattern,
std::vector<PatternConverterPtr>& patternConverters,
std::vector<FormattingInfoPtr>& formattingInfos,
const PatternMap& rules) {
LogString currentLiteral;
int patternLength = pattern.length();
int state = LITERAL_STATE;
logchar c;
int i = 0;
FormattingInfoPtr formattingInfo(FormattingInfo::getDefault());
while (i < patternLength) {
c = pattern[i++];
switch (state) {
case LITERAL_STATE:
// In literal state, the last char is always a literal.
if (i == patternLength) {
currentLiteral.append(1, c);
continue;
}
if (c == ESCAPE_CHAR) {
// peek at the next char.
if(pattern[i] == ESCAPE_CHAR) {
currentLiteral.append(1, c);
i++; // move pointer
} else {
if (!currentLiteral.empty()) {
patternConverters.push_back(
LiteralPatternConverter::newInstance(currentLiteral));
formattingInfos.push_back(FormattingInfo::getDefault());
currentLiteral.erase(currentLiteral.begin(), currentLiteral.end());
}
currentLiteral.append(1, c); // append %
state = CONVERTER_STATE;
formattingInfo = FormattingInfo::getDefault();
}
} else {
currentLiteral.append(1, c);
}
break;
case CONVERTER_STATE:
currentLiteral.append(1, c);
switch (c) {
case 0x2D: // '-'
formattingInfo =
new FormattingInfo(
true, formattingInfo->getMinLength(),
formattingInfo->getMaxLength());
break;
case 0x2E: // '.'
state = DOT_STATE;
break;
default:
if ((c >= 0x30 /* '0' */) && (c <= 0x39 /* '9' */)) {
formattingInfo =
new FormattingInfo(
formattingInfo->isLeftAligned(), c - 0x30 /* '0' */,
formattingInfo->getMaxLength());
state = MIN_STATE;
} else {
i = finalizeConverter(
c, pattern, i, currentLiteral, formattingInfo,
rules, patternConverters, formattingInfos);
// Next pattern is assumed to be a literal.
state = LITERAL_STATE;
formattingInfo = FormattingInfo::getDefault();
if (!currentLiteral.empty()) {
currentLiteral.erase(currentLiteral.begin(), currentLiteral.end());
}
}
} // switch
break;
case MIN_STATE:
currentLiteral.append(1, c);
if ((c >= 0x30 /* '0' */) && (c <= 0x39 /* '9' */)) {
formattingInfo =
new FormattingInfo(
formattingInfo->isLeftAligned(),
(formattingInfo->getMinLength() * 10) + (c - 0x30 /* '0' */),
formattingInfo->getMaxLength());
} else if (c == 0x2E /* '.' */) {
state = DOT_STATE;
} else {
i = finalizeConverter(
c, pattern, i, currentLiteral, formattingInfo,
rules, patternConverters, formattingInfos);
state = LITERAL_STATE;
formattingInfo = FormattingInfo::getDefault();
if (!currentLiteral.empty()) {
currentLiteral.erase(currentLiteral.begin(), currentLiteral.end());
}
}
break;
case DOT_STATE:
currentLiteral.append(1, c);
if ((c >= 0x30 /* '0' */) && (c <= 0x39 /* '9' */)) {
formattingInfo =
new FormattingInfo(
formattingInfo->isLeftAligned(), formattingInfo->getMinLength(),
c - 0x30 /* '0' */);
state = MAX_STATE;
} else {
LogLog::error(LOG4CXX_STR("Error in pattern, was expecting digit."));
state = LITERAL_STATE;
}
break;
case MAX_STATE:
currentLiteral.append(1, c);
if ((c >= 0x30 /* '0' */) && (c <= 0x39 /* '9' */)) {
formattingInfo =
new FormattingInfo(
formattingInfo->isLeftAligned(), formattingInfo->getMinLength(),
(formattingInfo->getMaxLength() * 10) + (c - 0x30 /* '0' */));
} else {
i = finalizeConverter(
c, pattern, i, currentLiteral, formattingInfo,
rules, patternConverters, formattingInfos);
state = LITERAL_STATE;
formattingInfo = FormattingInfo::getDefault();
if (!currentLiteral.empty()) {
currentLiteral.erase(currentLiteral.begin(), currentLiteral.end());
}
}
break;
} // switch
}
// while
if (currentLiteral.length() != 0) {
patternConverters.push_back(
LiteralPatternConverter::newInstance(currentLiteral));
formattingInfos.push_back(FormattingInfo::getDefault());
}
}
PatternConverterPtr PatternParser::createConverter(
const LogString& converterId,
LogString& currentLiteral,
const PatternMap& rules,
std::vector<LogString>& options) {
LogString converterName(converterId);
for (int i = converterId.length(); i > 0; i--) {
converterName = converterName.substr(0, i);
PatternMap::const_iterator iter = rules.find(converterName);
if (iter != rules.end()) {
currentLiteral.erase(currentLiteral.begin(),
currentLiteral.end() - (converterId.length() - i));
return (iter->second)(options);
}
}
LogLog::error(LogString(LOG4CXX_STR("Unrecognized format specifier ")) + converterId);
ObjectPtr converterObj;
return converterObj;
}
int PatternParser::finalizeConverter(
logchar c, const LogString& pattern, int i,
LogString& currentLiteral, const FormattingInfoPtr& formattingInfo,
const PatternMap& rules,
std::vector<PatternConverterPtr>& patternConverters,
std::vector<FormattingInfoPtr>& formattingInfos) {
LogString convBuf;
i = extractConverter(c, pattern, i, convBuf, currentLiteral);
if (convBuf.empty()) {
LogLog::error(LOG4CXX_STR("Empty conversion specifier"));
patternConverters.push_back(
LiteralPatternConverter::newInstance(currentLiteral));
formattingInfos.push_back(FormattingInfo::getDefault());
} else {
LogString converterId(convBuf);
std::vector<LogString> options;
i = extractOptions(pattern, i, options);
PatternConverterPtr pc(
createConverter(
converterId, currentLiteral, rules, options));
if (pc == NULL) {
LogString msg(LOG4CXX_STR("Unrecognized conversion specifier ["));
msg.append(converterId);
msg.append(LOG4CXX_STR("] in conversion pattern."));
LogLog::error(msg);
patternConverters.push_back(
LiteralPatternConverter::newInstance(currentLiteral));
formattingInfos.push_back(FormattingInfo::getDefault());
} else {
patternConverters.push_back(pc);
formattingInfos.push_back(formattingInfo);
if (currentLiteral.length() > 0) {
patternConverters.push_back(
LiteralPatternConverter::newInstance(currentLiteral));
formattingInfos.push_back(FormattingInfo::getDefault());
}
}
}
if (!currentLiteral.empty()) {
currentLiteral.erase(currentLiteral.begin(), currentLiteral.end());
}
return i;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/rolling/zipcompressaction.h>
#include <apr_thread_proc.h>
#include <apr_strings.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/helpers/transcoder.h>
using namespace log4cxx;
using namespace log4cxx::rolling;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(ZipCompressAction)
ZipCompressAction::ZipCompressAction(const File& src,
const File& dest,
bool del)
: source(src), destination(dest), deleteSource(del) {
}
bool ZipCompressAction::execute(log4cxx::helpers::Pool& p) const {
if (source.exists(p)) {
apr_pool_t* pool = p.getAPRPool();
apr_procattr_t* attr;
apr_status_t stat = apr_procattr_create(&attr, pool);
if (stat != APR_SUCCESS) throw IOException(stat);
stat = apr_procattr_io_set(attr, APR_NO_PIPE, APR_NO_PIPE, APR_FULL_BLOCK);
if (stat != APR_SUCCESS) throw IOException(stat);
stat = apr_procattr_cmdtype_set(attr, APR_PROGRAM_PATH);
if (stat != APR_SUCCESS) throw IOException(stat);
//
// redirect the child's error stream to this processes' error stream
//
apr_file_t* child_err;
stat = apr_file_open_stderr(&child_err, pool);
if (stat == APR_SUCCESS) {
stat = apr_procattr_child_err_set(attr, child_err, NULL);
if (stat != APR_SUCCESS) throw IOException(stat);
}
const char** args = (const char**)
apr_palloc(pool, 5 *sizeof(*args));
int i = 0;
args[i++] = "zip";
args[i++] = "-q";
args[i++] = Transcoder::encode(destination.getPath(), p);
args[i++] = Transcoder::encode(source.getPath(), p);
args[i++] = NULL;
if (destination.exists(p)) {
destination.deleteFile(p);
}
apr_proc_t pid;
stat = apr_proc_create(&pid, "zip", args, NULL, attr, pool);
if (stat != APR_SUCCESS) throw IOException(stat);
apr_proc_wait(&pid, NULL, NULL, APR_WAIT);
if (deleteSource) {
source.deleteFile(p);
}
return true;
}
return false;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/dailyrollingfileappender.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/rolling/rollingfileappender.h>
#include <log4cxx/rolling/timebasedrollingpolicy.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::rolling;
IMPLEMENT_LOG4CXX_OBJECT(DailyRollingFileAppender)
DailyRollingFileAppender::DailyRollingFileAppender()
{
}
DailyRollingFileAppender::DailyRollingFileAppender(
const LayoutPtr& layout,
const LogString& filename,
const LogString& datePattern1)
: datePattern(datePattern1) {
setLayout(layout);
setFile(filename);
Pool p;
activateOptions(p);
}
void DailyRollingFileAppender::setDatePattern(const LogString& pattern) {
datePattern = pattern;
}
LogString DailyRollingFileAppender::getDatePattern() {
return datePattern;
}
void DailyRollingFileAppender::activateOptions(log4cxx::helpers::Pool& pool) {
TimeBasedRollingPolicyPtr policy = new TimeBasedRollingPolicy();
LogString pattern(getFile());
bool inLiteral = false;
bool inPattern = false;
for (size_t i = 0; i < datePattern.length(); i++) {
if (datePattern[i] == 0x27 /* '\'' */) {
inLiteral = !inLiteral;
if (inLiteral && inPattern) {
pattern.append(1, (logchar) 0x7D /* '}' */);
inPattern = false;
}
} else {
if (!inLiteral && !inPattern) {
const logchar dbrace[] = { 0x25, 0x64, 0x7B, 0 }; // "%d{"
pattern.append(dbrace);
inPattern = true;
}
pattern.append(1, datePattern[i]);
}
}
if (inPattern) {
pattern.append(1, (logchar) 0x7D /* '}' */);
}
policy->setFileNamePattern(pattern);
policy->activateOptions(pool);
setTriggeringPolicy(policy);
setRollingPolicy(policy);
RollingFileAppenderSkeleton::activateOptions(pool);
}
void DailyRollingFileAppender::setOption(const LogString& option,
const LogString& value) {
if (StringHelper::equalsIgnoreCase(option,
LOG4CXX_STR("DATEPATTERN"), LOG4CXX_STR("datepattern"))) {
setDatePattern(value);
} else {
RollingFileAppenderSkeleton::setOption(option, value);
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/net/smtpappender.h>
#include <log4cxx/level.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/stringtokenizer.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/helpers/synchronized.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/private/log4cxx_private.h>
#include <apr_strings.h>
#include <vector>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::net;
using namespace log4cxx::spi;
#if LOG4CXX_HAVE_LIBESMTP
#include <auth-client.h>
#include <libesmtp.h>
#endif
namespace log4cxx {
namespace net {
//
// The following two classes implement an C++ SMTP wrapper over libesmtp.
// The same signatures could be implemented over different SMTP implementations
// or libesmtp could be combined with libgmime to enable support for non-ASCII
// content.
#if LOG4CXX_HAVE_LIBESMTP
/**
* SMTP Session.
*/
class SMTPSession {
public:
/**
* Create new instance.
*/
SMTPSession(const LogString& smtpHost,
int smtpPort,
const LogString& smtpUsername,
const LogString& smtpPassword,
Pool& p) : session(0), authctx(0),
user(toAscii(smtpUsername, p)),
pwd(toAscii(smtpPassword, p)) {
auth_client_init();
session = smtp_create_session();
if (session == 0) {
throw Exception("Could not initialize session.");
}
std::string host(toAscii(smtpHost, p));
host.append(1, ':');
host.append(p.itoa(smtpPort));
smtp_set_server(session, host.c_str());
authctx = auth_create_context();
auth_set_mechanism_flags(authctx, AUTH_PLUGIN_PLAIN, 0);
auth_set_interact_cb(authctx, authinteract, (void*) this);
if (*user || *pwd) {
smtp_auth_set_context(session, authctx);
}
}
~SMTPSession() {
smtp_destroy_session(session);
auth_destroy_context(authctx);
}
void send(Pool& p) {
int status = smtp_start_session(session);
if (!status) {
size_t bufSize = 128;
char* buf = p.pstralloc(bufSize);
smtp_strerror(smtp_errno(), buf, bufSize);
throw Exception(buf);
}
}
operator smtp_session_t() {
return session;
}
static char* toAscii(const LogString& str, Pool& p) {
char* buf = p.pstralloc(str.length() + 1);
char* current = buf;
for(LogString::const_iterator iter = str.begin();
iter != str.end();
iter++) {
unsigned int c = *iter;
if (c > 0x7F) {
c = '?';
}
*current++ = c;
}
*current = 0;
return buf;
}
private:
SMTPSession(SMTPSession&);
SMTPSession& operator=(SMTPSession&);
smtp_session_t session;
auth_context_t authctx;
char* user;
char* pwd;
/**
* This method is called if the SMTP server requests authentication.
*/
static int authinteract(auth_client_request_t request, char **result, int fields,
void *arg) {
SMTPSession* pThis = (SMTPSession*) arg;
for (int i = 0; i < fields; i++) {
int flag = request[i].flags & 0x07;
if (flag == AUTH_USER) {
result[i] = pThis->user;
} else if(flag == AUTH_PASS) {
result[i] = pThis->pwd;
}
}
return 1;
}
};
/**
* A message in an SMTP session.
*/
class SMTPMessage {
public:
SMTPMessage(SMTPSession& session,
const LogString& from,
const LogString& to,
const LogString& cc,
const LogString& bcc,
const LogString& subject,
const LogString msg, Pool& p) {
message = smtp_add_message(session);
body = current = toMessage(msg, p);
smtp_set_reverse_path(message, toAscii(from, p));
addRecipients(to, "To", p);
addRecipients(cc, "Cc", p);
addRecipients(bcc, "Bcc", p);
if (!subject.empty()) {
smtp_set_header(message, "Subject", toAscii(subject, p));
}
smtp_set_messagecb(message, messagecb, this);
}
~SMTPMessage() {
}
private:
SMTPMessage(const SMTPMessage&);
SMTPMessage& operator=(const SMTPMessage&);
smtp_message_t message;
const char* body;
const char* current;
void addRecipients(const LogString& addresses, const char* field, Pool& p) {
if (!addresses.empty()) {
char* str = p.pstrdup(toAscii(addresses, p));;
smtp_set_header(message, field, NULL, str);
char* last;
for(char* next = apr_strtok(str, ",", &last);
next;
next = apr_strtok(NULL, ",", &last)) {
smtp_add_recipient(message, next);
}
}
}
static const char* toAscii(const LogString& str, Pool& p) {
return SMTPSession::toAscii(str, p);
}
/**
* Message bodies can only contain US-ASCII characters and
* CR and LFs can only occur together.
*/
static const char* toMessage(const LogString& str, Pool& p) {
//
// count the number of carriage returns and line feeds
//
int feedCount = 0;
for(size_t pos = str.find_first_of(LOG4CXX_STR("\n\r"));
pos != LogString::npos;
pos = str.find_first_of(LOG4CXX_STR("\n\r"), ++pos)) {
feedCount++;
}
//
// allocate sufficient space for the modified message
char* retval = p.pstralloc(str.length() + feedCount + 1);
char* current = retval;
char* startOfLine = current;
//
// iterator through message
//
for(LogString::const_iterator iter = str.begin();
iter != str.end();
iter++) {
unsigned int c = *iter;
//
// replace non-ASCII characters with '?'
//
if (c > 0x7F) {
*current++ = 0x3F; // '?'
} else if (c == 0x0A || c == 0x0D) {
//
// replace any stray CR or LF with CRLF
// reset start of line
*current++ = 0x0D;
*current++ = 0x0A;
startOfLine = current;
LogString::const_iterator next = iter + 1;
if (next != str.end() && (*next == 0x0A || *next == 0x0D)) {
iter++;
}
} else {
//
// truncate any lines to 1000 characters (including CRLF)
// as required by RFC.
if (current < startOfLine + 998) {
*current++ = (char) c;
}
}
}
*current = 0;
return retval;
}
/**
* Callback for message.
*/
static const char* messagecb(void** ctx, int* len, void* arg) {
*ctx = 0;
const char* retval = 0;
SMTPMessage* pThis = (SMTPMessage*) arg;
// rewind message
if (len == NULL) {
pThis->current = pThis->body;
} else {
if (pThis->current) {
*len = strlen(pThis->current);
}
retval = pThis->current;
pThis->current = 0;
}
return retval;
}
};
#endif
class LOG4CXX_EXPORT DefaultEvaluator :
public virtual spi::TriggeringEventEvaluator,
public virtual helpers::ObjectImpl
{
public:
DECLARE_LOG4CXX_OBJECT(DefaultEvaluator)
BEGIN_LOG4CXX_CAST_MAP()
LOG4CXX_CAST_ENTRY(DefaultEvaluator)
LOG4CXX_CAST_ENTRY(spi::TriggeringEventEvaluator)
END_LOG4CXX_CAST_MAP()
DefaultEvaluator();
/**
Is this <code>event</code> the e-mail triggering event?
<p>This method returns <code>true</code>, if the event level
has ERROR level or higher. Otherwise it returns
<code>false</code>.
*/
virtual bool isTriggeringEvent(const spi::LoggingEventPtr& event);
private:
DefaultEvaluator(const DefaultEvaluator&);
DefaultEvaluator& operator=(const DefaultEvaluator&);
}; // class DefaultEvaluator
}
}
IMPLEMENT_LOG4CXX_OBJECT(DefaultEvaluator)
IMPLEMENT_LOG4CXX_OBJECT(SMTPAppender)
DefaultEvaluator::DefaultEvaluator() {
}
bool DefaultEvaluator::isTriggeringEvent(const spi::LoggingEventPtr& event)
{
return event->getLevel()->isGreaterOrEqual(Level::getError());
}
SMTPAppender::SMTPAppender()
: smtpPort(25), bufferSize(512), locationInfo(false), cb(bufferSize),
evaluator(new DefaultEvaluator())
{
}
/**
Use <code>evaluator</code> passed as parameter as the
TriggeringEventEvaluator for this SMTPAppender. */
SMTPAppender::SMTPAppender(spi::TriggeringEventEvaluatorPtr evaluator)
: smtpPort(25), bufferSize(512), locationInfo(false), cb(bufferSize),
evaluator(evaluator)
{
}
SMTPAppender::~SMTPAppender()
{
finalize();
}
bool SMTPAppender::requiresLayout() const {
return true;
}
LogString SMTPAppender::getFrom() const {
return from;
}
void SMTPAppender::setFrom(const LogString& newVal) {
from = newVal;
}
LogString SMTPAppender::getSubject() const {
return subject;
}
void SMTPAppender::setSubject(const LogString& newVal) {
subject = newVal;
}
LogString SMTPAppender::getSMTPHost() const {
return smtpHost;
}
void SMTPAppender::setSMTPHost(const LogString& newVal) {
smtpHost = newVal;
}
int SMTPAppender::getSMTPPort() const {
return smtpPort;
}
void SMTPAppender::setSMTPPort(int newVal) {
smtpPort = newVal;
}
bool SMTPAppender::getLocationInfo() const {
return locationInfo;
}
void SMTPAppender::setLocationInfo(bool newVal) {
locationInfo = newVal;
}
LogString SMTPAppender::getSMTPUsername() const {
return smtpUsername;
}
void SMTPAppender::setSMTPUsername(const LogString& newVal) {
smtpUsername = newVal;
}
LogString SMTPAppender::getSMTPPassword() const {
return smtpPassword;
}
void SMTPAppender::setSMTPPassword(const LogString& newVal) {
smtpPassword = newVal;
}
void SMTPAppender::setOption(const LogString& option,
const LogString& value)
{
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFERSIZE"), LOG4CXX_STR("buffersize")))
{
setBufferSize(OptionConverter::toInt(value, 512));
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("EVALUATORCLASS"), LOG4CXX_STR("evaluatorclass")))
{
setEvaluatorClass(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("FROM"), LOG4CXX_STR("from")))
{
setFrom(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPHOST"), LOG4CXX_STR("smtphost")))
{
setSMTPHost(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPUSERNAME"), LOG4CXX_STR("smtpusername")))
{
setSMTPUsername(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPPASSWORD"), LOG4CXX_STR("smtppassword")))
{
setSMTPPassword(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SUBJECT"), LOG4CXX_STR("subject")))
{
setSubject(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("TO"), LOG4CXX_STR("to")))
{
setTo(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("CC"), LOG4CXX_STR("cc")))
{
setCc(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BCC"), LOG4CXX_STR("bcc")))
{
setBcc(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPPORT"), LOG4CXX_STR("smtpport")))
{
setSMTPPort(OptionConverter::toInt(value, 25));
}
else
{
AppenderSkeleton::setOption(option, value);
}
}
bool SMTPAppender::asciiCheck(const LogString& value, const LogString& field) {
for(LogString::const_iterator iter = value.begin();
iter != value.end();
iter++) {
if (0x7F < (unsigned int) *iter) {
LogLog::warn(field + LOG4CXX_STR(" contains non-ASCII character"));
return false;
}
}
return true;
}
/**
Activate the specified options, such as the smtp host, the
recipient, from, etc. */
void SMTPAppender::activateOptions(Pool& p)
{
bool activate = true;
if (layout == 0) {
LogLog::error(LOG4CXX_STR("No layout set for appender named [") +name+ LOG4CXX_STR("]."));
activate = false;
}
if(evaluator == 0) {
LogLog::error(LOG4CXX_STR("No TriggeringEventEvaluator is set for appender [")+
name+LOG4CXX_STR("]."));
activate = false;
}
if(smtpHost.empty()) {
LogLog::error(LOG4CXX_STR("No smtpHost is set for appender [")+
name+LOG4CXX_STR("]."));
activate = false;
}
if(to.empty() && cc.empty() && bcc.empty()) {
LogLog::error(LOG4CXX_STR("No recipient address is set for appender [")+
name+LOG4CXX_STR("]."));
activate = false;
}
activate &= asciiCheck(to, LOG4CXX_STR("to"));
activate &= asciiCheck(cc, LOG4CXX_STR("cc"));
activate &= asciiCheck(bcc, LOG4CXX_STR("bcc"));
activate &= asciiCheck(from, LOG4CXX_STR("from"));
#if !LOG4CXX_HAS_LIBESMTP
LogLog::error(LOG4CXX_STR("log4cxx built without SMTP support."));
activate = false;
#endif
if (activate) {
AppenderSkeleton::activateOptions(p);
}
}
/**
Perform SMTPAppender specific appending actions, mainly adding
the event to a cyclic buffer and checking if the event triggers
an e-mail to be sent. */
void SMTPAppender::append(const spi::LoggingEventPtr& event, Pool& p)
{
if(!checkEntryConditions())
{
return;
}
LogString ndc;
event->getNDC(ndc);
event->getThreadName();
// Get a copy of this thread's MDC.
event->getMDCCopy();
cb.add(event);
if(evaluator->isTriggeringEvent(event))
{
sendBuffer(p);
}
}
/**
This method determines if there is a sense in attempting to append.
<p>It checks whether there is a set output target and also if
there is a set layout. If these checks fail, then the boolean
value <code>false</code> is returned. */
bool SMTPAppender::checkEntryConditions()
{
#if LOG4CXX_HAVE_LIBESMTP
if((to.empty() && cc.empty() && bcc.empty()) || from.empty() || smtpHost.empty())
{
errorHandler->error(LOG4CXX_STR("Message not configured."));
return false;
}
if(evaluator == 0)
{
errorHandler->error(LOG4CXX_STR("No TriggeringEventEvaluator is set for appender [")+
name+ LOG4CXX_STR("]."));
return false;
}
if(layout == 0)
{
errorHandler->error(LOG4CXX_STR("No layout set for appender named [")+name+LOG4CXX_STR("]."));
return false;
}
return true;
#else
return false;
#endif
}
void SMTPAppender::close() {
this->closed = true;
}
LogString SMTPAppender::getTo() const{
return to;
}
void SMTPAppender::setTo(const LogString& addressStr) {
to = addressStr;
}
LogString SMTPAppender::getCc() const{
return cc;
}
void SMTPAppender::setCc(const LogString& addressStr) {
cc = addressStr;
}
LogString SMTPAppender::getBcc() const{
return bcc;
}
void SMTPAppender::setBcc(const LogString& addressStr) {
bcc = addressStr;
}
/**
Send the contents of the cyclic buffer as an e-mail message.
*/
void SMTPAppender::sendBuffer(Pool& p)
{
#if LOG4CXX_HAS_LIBESMTP
// Note: this code already owns the monitor for this
// appender. This frees us from needing to synchronize on 'cb'.
try
{
LogString sbuf;
layout->appendHeader(sbuf, p);
int len = cb.length();
for(int i = 0; i < len; i++)
{
LoggingEventPtr event = cb.get();
layout->format(sbuf, event, p);
}
layout->appendFooter(sbuf, p);
SMTPSession session(smtpHost, smtpPort, smtpUsername, smtpPassword, p);
SMTPMessage message(session, from, to, cc,
bcc, subject, sbuf, p);
session.send(p);
}
catch(std::exception& e)
{
LogLog::error(LOG4CXX_STR("Error occured while sending e-mail notification."), e);
}
#endif
}
/**
Returns value of the <b>EvaluatorClass</b> option.
*/
LogString SMTPAppender::getEvaluatorClass()
{
return evaluator == 0 ? LogString() : evaluator->getClass().getName();
}
log4cxx::spi::TriggeringEventEvaluatorPtr SMTPAppender::getEvaluator() const {
return evaluator;
}
void SMTPAppender::setEvaluator(log4cxx::spi::TriggeringEventEvaluatorPtr& trigger) {
evaluator = trigger;
}
/**
The <b>BufferSize</b> option takes a positive integer
representing the maximum number of logging events to collect in a
cyclic buffer. When the <code>BufferSize</code> is reached,
oldest events are deleted as new events are added to the
buffer. By default the size of the cyclic buffer is 512 events.
*/
void SMTPAppender::setBufferSize(int bufferSize)
{
this->bufferSize = bufferSize;
cb.resize(bufferSize);
}
/**
The <b>EvaluatorClass</b> option takes a string value
representing the name of the class implementing the {@link
TriggeringEventEvaluator} interface. A corresponding object will
be instantiated and assigned as the triggering event evaluator
for the SMTPAppender.
*/
void SMTPAppender::setEvaluatorClass(const LogString& value)
{
evaluator = OptionConverter::instantiateByClassName(value,
TriggeringEventEvaluator::getStaticClass(), evaluator);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/htmllayout.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/level.h>
#include <log4cxx/helpers/transform.h>
#include <log4cxx/helpers/iso8601dateformat.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/transcoder.h>
#include <apr_time.h>
#include <apr_strings.h>
#include <string.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
IMPLEMENT_LOG4CXX_OBJECT(HTMLLayout)
HTMLLayout::HTMLLayout()
: locationInfo(false), title(LOG4CXX_STR("Log4cxx Log Messages")),
dateFormat()
{
dateFormat.setTimeZone(TimeZone::getGMT());
}
void HTMLLayout::setOption(const LogString& option,
const LogString& value)
{
if (StringHelper::equalsIgnoreCase(option,
LOG4CXX_STR("TITLE"), LOG4CXX_STR("title")))
{
setTitle(value);
}
else if (StringHelper::equalsIgnoreCase(option,
LOG4CXX_STR("LOCATIONINFO"), LOG4CXX_STR("locationinfo")))
{
setLocationInfo(OptionConverter::toBoolean(value, false));
}
}
void HTMLLayout::format(LogString& output,
const spi::LoggingEventPtr& event,
Pool& p) const
{
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<tr>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<td>"));
dateFormat.format(output, event->getTimeStamp(), p);
output.append(LOG4CXX_STR("</td>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<td title=\""));
LogString threadName(event->getThreadName());
output.append(threadName);
output.append(LOG4CXX_STR(" thread\">"));
output.append(threadName);
output.append(LOG4CXX_STR("</td>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<td title=\"Level\">"));
if (event->getLevel()->equals(Level::getDebug()))
{
output.append(LOG4CXX_STR("<font color=\"#339933\">"));
output.append(event->getLevel()->toString());
output.append(LOG4CXX_STR("</font>"));
}
else if(event->getLevel()->isGreaterOrEqual(Level::getWarn()))
{
output.append(LOG4CXX_STR("<font color=\"#993300\"><strong>"));
output.append(event->getLevel()->toString());
output.append(LOG4CXX_STR("</strong></font>"));
}
else
{
output.append(event->getLevel()->toString());
}
output.append(LOG4CXX_STR("</td>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<td title=\""));
output.append(event->getLoggerName());
output.append(LOG4CXX_STR(" logger\">"));
Transform::appendEscapingTags(output, event->getLoggerName());
output.append(LOG4CXX_STR("</td>"));
output.append(LOG4CXX_EOL);
if(locationInfo)
{
output.append(LOG4CXX_STR("<td>"));
const LocationInfo& locInfo = event->getLocationInformation();
LOG4CXX_DECODE_CHAR(fileName, locInfo.getFileName());
Transform::appendEscapingTags(output, fileName);
output.append(1, (logchar) 0x3A /* ':' */);
int line = event->getLocationInformation().getLineNumber();
if (line != 0)
{
StringHelper::toString(line, p, output);
}
output.append(LOG4CXX_STR("</td>"));
output.append(LOG4CXX_EOL);
}
output.append(LOG4CXX_STR("<td title=\"Message\">"));
Transform::appendEscapingTags(output, event->getRenderedMessage());
output.append(LOG4CXX_STR("</td>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("</tr>"));
output.append(LOG4CXX_EOL);
LogString ndcVal;
if (event->getNDC(ndcVal))
{
output.append(LOG4CXX_STR("<tr><td bgcolor=\"#EEEEEE\" "));
output.append(LOG4CXX_STR("style=\"font-size : xx-small;\" colspan=\"6\" "));
output.append(LOG4CXX_STR("title=\"Nested Diagnostic Context\">"));
output.append(LOG4CXX_STR("NDC: "));
Transform::appendEscapingTags(output, ndcVal);
output.append(LOG4CXX_STR("</td></tr>"));
output.append(LOG4CXX_EOL);
}
}
void HTMLLayout::appendHeader(LogString& output, Pool& p)
{
output.append(LOG4CXX_STR("<!DOCTYPE HTML PUBLIC "));
output.append(LOG4CXX_STR("\"-//W3C//DTD HTML 4.01 Transitional//EN\" "));
output.append(LOG4CXX_STR("\"http://www.w3.org/TR/html4/loose.dtd\">"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<html>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<head>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<title>"));
output.append(title);
output.append(LOG4CXX_STR("</title>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<style type=\"text/css\">"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<!--"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("body, table {font-family: arial,sans-serif; font-size: x-small;}"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("th {background: #336699; color: #FFFFFF; text-align: left;}"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("-->"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("</style>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("</head>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<body bgcolor=\"#FFFFFF\" topmargin=\"6\" leftmargin=\"6\">"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<hr size=\"1\" noshade>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("Log session start time "));
dateFormat.format(output, apr_time_now(), p);
output.append(LOG4CXX_STR("<br>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<br>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<table cellspacing=\"0\" cellpadding=\"4\" border=\"1\" bordercolor=\"#224466\" width=\"100%\">"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<tr>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<th>Time</th>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<th>Thread</th>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<th>Level</th>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<th>Logger</th>"));
output.append(LOG4CXX_EOL);
if(locationInfo)
{
output.append(LOG4CXX_STR("<th>File:Line</th>"));
output.append(LOG4CXX_EOL);
}
output.append(LOG4CXX_STR("<th>Message</th>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("</tr>"));
output.append(LOG4CXX_EOL);
}
void HTMLLayout::appendFooter(LogString& output, Pool& /* pool */ )
{
output.append(LOG4CXX_STR("</table>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<br>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("</body></html>"));
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/consoleappender.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/systemoutwriter.h>
#include <log4cxx/helpers/systemerrwriter.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/layout.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(ConsoleAppender)
ConsoleAppender::ConsoleAppender()
: target(getSystemOut())
{
}
ConsoleAppender::ConsoleAppender(const LayoutPtr& layout1)
:target(getSystemOut())
{
setLayout(layout1);
WriterPtr wr(createWriter(getSystemOut()));
setWriter(wr);
Pool p;
WriterAppender::activateOptions(p);
}
ConsoleAppender::ConsoleAppender(const LayoutPtr& layout1, const LogString& target1)
: target(target1)
{
setLayout(layout1);
WriterPtr wr(createWriter(target1));
setWriter(wr);
Pool p;
WriterAppender::activateOptions(p);
}
ConsoleAppender::~ConsoleAppender()
{
finalize();
}
const LogString& ConsoleAppender::getSystemOut() {
static const LogString name(LOG4CXX_STR("System.out"));
return name;
}
const LogString& ConsoleAppender::getSystemErr() {
static const LogString name(LOG4CXX_STR("System.err"));
return name;
}
WriterPtr ConsoleAppender::createWriter(const LogString& value) {
LogString v = StringHelper::trim(value);
if (StringHelper::equalsIgnoreCase(v,
LOG4CXX_STR("SYSTEM.ERR"), LOG4CXX_STR("system.err"))) {
return new SystemErrWriter();
}
return new SystemOutWriter();
}
void ConsoleAppender::setTarget(const LogString& value)
{
LogString v = StringHelper::trim(value);
if (StringHelper::equalsIgnoreCase(v,
LOG4CXX_STR("SYSTEM.OUT"), LOG4CXX_STR("system.out")))
{
target = getSystemOut();
}
else if (StringHelper::equalsIgnoreCase(v,
LOG4CXX_STR("SYSTEM.ERR"), LOG4CXX_STR("system.err")))
{
target = getSystemErr();
}
else
{
targetWarn(value);
}
}
LogString ConsoleAppender::getTarget() const
{
return target;
}
void ConsoleAppender::targetWarn(const LogString& val)
{
LogLog::warn(((LogString) LOG4CXX_STR("["))
+ val + LOG4CXX_STR("] should be system.out or system.err."));
LogLog::warn(LOG4CXX_STR("Using previously set target, System.out by default."));
}
void ConsoleAppender::activateOptions(Pool& p)
{
if(StringHelper::equalsIgnoreCase(target,
LOG4CXX_STR("SYSTEM.OUT"), LOG4CXX_STR("system.out")))
{
WriterPtr writer1(new SystemOutWriter());
setWriter(writer1);
}
else if (StringHelper::equalsIgnoreCase(target,
LOG4CXX_STR("SYSTEM.ERR"), LOG4CXX_STR("system.err")))
{
WriterPtr writer1(new SystemErrWriter());
setWriter(writer1);
}
WriterAppender::activateOptions(p);
}
void ConsoleAppender::setOption(const LogString& option, const LogString& value)
{
if (StringHelper::equalsIgnoreCase(option,
LOG4CXX_STR("TARGET"), LOG4CXX_STR("target")))
{
setTarget(value);
}
else
{
WriterAppender::setOption(option, value);
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/spi/loggerfactory.h>
#include <log4cxx/helpers/properties.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/level.h>
#include <log4cxx/defaultloggerfactory.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/appender.h>
#include <log4cxx/logger.h>
#include <log4cxx/layout.h>
#include <log4cxx/config/propertysetter.h>
#include <log4cxx/spi/loggerrepository.h>
#include <log4cxx/helpers/stringtokenizer.h>
#include <log4cxx/helpers/synchronized.h>
#include <apr_file_io.h>
#include <apr_file_info.h>
#include <apr_pools.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/helpers/fileinputstream.h>
using namespace log4cxx;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
using namespace log4cxx::config;
#if APR_HAS_THREADS
#include <log4cxx/helpers/filewatchdog.h>
class PropertyWatchdog : public FileWatchdog
{
public:
PropertyWatchdog(const File& filename) : FileWatchdog(filename)
{
}
/**
Call PropertyConfigurator#doConfigure(const String& configFileName,
const spi::LoggerRepositoryPtr& hierarchy) with the
<code>filename</code> to reconfigure log4cxx.
*/
void doOnChange()
{
PropertyConfigurator().doConfigure(file,
LogManager::getLoggerRepository());
}
};
#endif
IMPLEMENT_LOG4CXX_OBJECT(PropertyConfigurator)
PropertyConfigurator::PropertyConfigurator()
: registry(new std::map<LogString, AppenderPtr>()), loggerFactory(new DefaultLoggerFactory())
{
}
PropertyConfigurator::~PropertyConfigurator() {
delete registry;
}
void PropertyConfigurator::addRef() const {
ObjectImpl::addRef();
}
void PropertyConfigurator::releaseRef() const {
ObjectImpl::releaseRef();
}
void PropertyConfigurator::doConfigure(const File& configFileName,
spi::LoggerRepositoryPtr& hierarchy)
{
hierarchy->setConfigured(true);
Properties props;
try {
InputStreamPtr inputStream = new FileInputStream(configFileName);
props.load(inputStream);
} catch(const IOException& ie) {
LogLog::error(((LogString) LOG4CXX_STR("Could not read configuration file ["))
+ configFileName.getPath() + LOG4CXX_STR("]."));
return;
}
try {
doConfigure(props, hierarchy);
} catch(const std::exception& ex) {
LogLog::error(((LogString) LOG4CXX_STR("Could not parse configuration file ["))
+ configFileName.getPath() + LOG4CXX_STR("]."), ex);
}
}
void PropertyConfigurator::configure(const File& configFilename)
{
PropertyConfigurator().doConfigure(configFilename, LogManager::getLoggerRepository());
}
void PropertyConfigurator::configure(helpers::Properties& properties)
{
PropertyConfigurator().doConfigure(properties, LogManager::getLoggerRepository());
}
#if APR_HAS_THREADS
void PropertyConfigurator::configureAndWatch(const File& configFilename)
{
configureAndWatch(configFilename, FileWatchdog::DEFAULT_DELAY);
}
void PropertyConfigurator::configureAndWatch(
const File& configFilename, long delay)
{
PropertyWatchdog * pdog = new PropertyWatchdog(configFilename);
pdog->setDelay(delay);
pdog->start();
}
#endif
void PropertyConfigurator::doConfigure(helpers::Properties& properties,
spi::LoggerRepositoryPtr& hierarchy)
{
hierarchy->setConfigured(true);
static const LogString DEBUG_KEY(LOG4CXX_STR("log4j.debug"));
LogString value(properties.getProperty(DEBUG_KEY));
if (!value.empty())
{
LogLog::setInternalDebugging(OptionConverter::toBoolean(value, true));
}
static const LogString THRESHOLD_PREFIX(LOG4CXX_STR("log4j.threshold"));
LogString thresholdStr =
OptionConverter::findAndSubst(THRESHOLD_PREFIX, properties);
if (!thresholdStr.empty())
{
hierarchy->setThreshold(OptionConverter::toLevel(thresholdStr, Level::getAll()));
LogLog::debug(((LogString) LOG4CXX_STR("Hierarchy threshold set to ["))
+ hierarchy->getThreshold()->toString()
+ LOG4CXX_STR("]."));
}
configureRootLogger(properties, hierarchy);
configureLoggerFactory(properties);
parseCatsAndRenderers(properties, hierarchy);
LogLog::debug(LOG4CXX_STR("Finished configuring."));
// We don't want to hold references to appenders preventing their
// destruction.
registry->clear();
}
void PropertyConfigurator::configureLoggerFactory(helpers::Properties& props)
{
static const LogString LOGGER_FACTORY_KEY(LOG4CXX_STR("log4j.loggerFactory"));
LogString factoryClassName =
OptionConverter::findAndSubst(LOGGER_FACTORY_KEY, props);
if (!factoryClassName.empty())
{
LogString msg(LOG4CXX_STR("Setting logger factory to ["));
msg += factoryClassName;
msg += LOG4CXX_STR("].");
LogLog::debug(msg);
loggerFactory =
OptionConverter::instantiateByClassName(
factoryClassName, LoggerFactory::getStaticClass(), loggerFactory);
static const LogString FACTORY_PREFIX(LOG4CXX_STR("log4j.factory."));
Pool p;
PropertySetter::setProperties(loggerFactory, props, FACTORY_PREFIX, p);
}
}
void PropertyConfigurator::configureRootLogger(helpers::Properties& props,
spi::LoggerRepositoryPtr& hierarchy)
{
static const LogString ROOT_CATEGORY_PREFIX(LOG4CXX_STR("log4j.rootCategory"));
static const LogString ROOT_LOGGER_PREFIX(LOG4CXX_STR("log4j.rootLogger"));
LogString effectiveFrefix(ROOT_LOGGER_PREFIX);
LogString value = OptionConverter::findAndSubst(ROOT_LOGGER_PREFIX, props);
if (value.empty())
{
value = OptionConverter::findAndSubst(ROOT_CATEGORY_PREFIX, props);
effectiveFrefix = ROOT_CATEGORY_PREFIX;
}
if (value.empty())
{
LogLog::debug(LOG4CXX_STR("Could not find root logger information. Is this OK?"));
}
else
{
LoggerPtr root = hierarchy->getRootLogger();
synchronized sync(root->getMutex());
static const LogString INTERNAL_ROOT_NAME(LOG4CXX_STR("root"));
parseLogger(props, root, effectiveFrefix, INTERNAL_ROOT_NAME, value);
}
}
void PropertyConfigurator::parseCatsAndRenderers(helpers::Properties& props,
spi::LoggerRepositoryPtr& hierarchy)
{
static const LogString CATEGORY_PREFIX(LOG4CXX_STR("log4j.category."));
static const LogString LOGGER_PREFIX(LOG4CXX_STR("log4j.logger."));
std::vector<LogString> names = props.propertyNames();
std::vector<LogString>::iterator it = names.begin();
std::vector<LogString>::iterator itEnd = names.end();
while (it != itEnd)
{
LogString key = *it++;
if (key.find(CATEGORY_PREFIX) == 0 || key.find(LOGGER_PREFIX) == 0)
{
LogString loggerName;
if (key.find(CATEGORY_PREFIX) == 0)
{
loggerName = key.substr(CATEGORY_PREFIX.length());
}
else if (key.find(LOGGER_PREFIX) == 0)
{
loggerName = key.substr(LOGGER_PREFIX.length());
}
LogString value = OptionConverter::findAndSubst(key, props);
LoggerPtr logger = hierarchy->getLogger(loggerName, loggerFactory);
synchronized sync(logger->getMutex());
parseLogger(props, logger, key, loggerName, value);
parseAdditivityForLogger(props, logger, loggerName);
}
}
}
void PropertyConfigurator::parseAdditivityForLogger(helpers::Properties& props,
LoggerPtr& cat, const LogString& loggerName)
{
static const LogString ADDITIVITY_PREFIX(LOG4CXX_STR("log4j.additivity."));
LogString value(OptionConverter::findAndSubst(ADDITIVITY_PREFIX + loggerName, props));
LogLog::debug((LogString) LOG4CXX_STR("Handling ") + ADDITIVITY_PREFIX
+ loggerName + LOG4CXX_STR("=[") + value + LOG4CXX_STR("]"));
// touch additivity only if necessary
if (!value.empty())
{
bool additivity = OptionConverter::toBoolean(value, true);
LogLog::debug(((LogString) LOG4CXX_STR("Setting additivity for \""))
+ loggerName
+ ((additivity) ? LOG4CXX_STR("\" to true") :
LOG4CXX_STR("\" to false")));
cat->setAdditivity(additivity);
}
}
/**
This method must work for the root logger as well.
*/
void PropertyConfigurator::parseLogger(
helpers::Properties& props, LoggerPtr& logger, const LogString& /* optionKey */,
const LogString& loggerName, const LogString& value)
{
LogLog::debug(((LogString) LOG4CXX_STR("Parsing for ["))
+ loggerName
+ LOG4CXX_STR("] with value=[")
+ value + LOG4CXX_STR("]."));
// We must skip over ',' but not white space
StringTokenizer st(value, LOG4CXX_STR(","));
// If value is not in the form ", appender.." or "", then we should set
// the level of the logger.
if (!(value.find(LOG4CXX_STR(",")) == 0 || value.empty()))
{
// just to be on the safe side...
if (!st.hasMoreTokens())
{
return;
}
LogString levelStr = st.nextToken();
LogLog::debug((LogString) LOG4CXX_STR("Level token is [")
+ levelStr + LOG4CXX_STR("]."));
// If the level value is inherited, set logger level value to
// null. We also check that the user has not specified inherited for the
// root logger.
if (StringHelper::equalsIgnoreCase(levelStr, LOG4CXX_STR("INHERITED"), LOG4CXX_STR("inherited"))
|| StringHelper::equalsIgnoreCase(levelStr, LOG4CXX_STR("NULL"), LOG4CXX_STR("null")))
{
static const LogString INTERNAL_ROOT_NAME(LOG4CXX_STR("root"));
if (loggerName == INTERNAL_ROOT_NAME)
{
LogLog::warn(LOG4CXX_STR("The root logger cannot be set to null."));
}
else
{
logger->setLevel(0);
LogLog::debug((LogString) LOG4CXX_STR("Logger ")
+ loggerName + LOG4CXX_STR(" set to null"));
}
}
else
{
logger->setLevel(OptionConverter::toLevel(levelStr, Level::getDebug()));
LogLog::debug((LogString) LOG4CXX_STR("Logger ")
+ loggerName + LOG4CXX_STR(" set to ")
+ logger->getLevel()->toString());
}
}
// Begin by removing all existing appenders.
logger->removeAllAppenders();
AppenderPtr appender;
LogString appenderName;
while (st.hasMoreTokens())
{
appenderName = StringHelper::trim(st.nextToken());
if (appenderName.empty() || appenderName == LOG4CXX_STR(","))
{
continue;
}
LogLog::debug(LOG4CXX_STR("Parsing appender named ")
+ appenderName + LOG4CXX_STR("\"."));
appender = parseAppender(props, appenderName);
if (appender != 0)
{
logger->addAppender(appender);
}
}
}
AppenderPtr PropertyConfigurator::parseAppender(
helpers::Properties& props, const LogString& appenderName)
{
AppenderPtr appender = registryGet(appenderName);
if (appender != 0)
{
LogLog::debug((LogString) LOG4CXX_STR("Appender \"")
+ appenderName + LOG4CXX_STR("\" was already parsed."));
return appender;
}
static const LogString APPENDER_PREFIX(LOG4CXX_STR("log4j.appender."));
// Appender was not previously initialized.
LogString prefix = APPENDER_PREFIX + appenderName;
LogString layoutPrefix = prefix + LOG4CXX_STR(".layout");
appender =
OptionConverter::instantiateByKey(
props, prefix, Appender::getStaticClass(), 0);
if (appender == 0)
{
LogLog::error((LogString) LOG4CXX_STR("Could not instantiate appender named \"")
+ appenderName + LOG4CXX_STR("\"."));
return 0;
}
appender->setName(appenderName);
if (appender->instanceof(OptionHandler::getStaticClass()))
{
Pool p;
if (appender->requiresLayout())
{
LayoutPtr layout =
OptionConverter::instantiateByKey(
props, layoutPrefix, Layout::getStaticClass(), 0);
if (layout != 0)
{
appender->setLayout(layout);
LogLog::debug((LogString) LOG4CXX_STR("Parsing layout options for \"")
+ appenderName + LOG4CXX_STR("\"."));
//configureOptionHandler(layout, layoutPrefix + ".", props);
PropertySetter::setProperties(layout, props, layoutPrefix + LOG4CXX_STR("."), p);
LogLog::debug((LogString) LOG4CXX_STR("End of parsing for \"")
+ appenderName + LOG4CXX_STR("\"."));
}
}
//configureOptionHandler((OptionHandler) appender, prefix + _T("."), props);
PropertySetter::setProperties(appender, props, prefix + LOG4CXX_STR("."), p);
LogLog::debug((LogString) LOG4CXX_STR("Parsed \"")
+ appenderName + LOG4CXX_STR("\" options."));
}
registryPut(appender);
return appender;
}
void PropertyConfigurator::registryPut(const AppenderPtr& appender)
{
(*registry)[appender->getName()] = appender;
}
AppenderPtr PropertyConfigurator::registryGet(const LogString& name)
{
return (*registry)[name];
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/helpers/serversocket.h>
#include <log4cxx/helpers/synchronized.h>
#include "apr_network_io.h"
#include "apr_pools.h"
#include "apr_poll.h"
using namespace log4cxx::helpers;
/** Creates a server socket on a specified port.
*/
ServerSocket::ServerSocket(int port) : pool(), mutex(pool), socket(0), timeout(0)
{
apr_status_t status =
apr_socket_create(&socket, APR_INET, SOCK_STREAM,
APR_PROTO_TCP, pool.getAPRPool());
if (status != APR_SUCCESS) {
throw SocketException(status);
}
status = apr_socket_opt_set(socket, APR_SO_NONBLOCK, 1);
if (status != APR_SUCCESS) {
throw SocketException(status);
}
// Create server socket address (including port number)
apr_sockaddr_t *server_addr;
status =
apr_sockaddr_info_get(&server_addr, NULL, APR_INET,
port, 0, pool.getAPRPool());
if (status != APR_SUCCESS) {
throw ConnectException(status);
}
// bind the socket to the address
status = apr_socket_bind(socket, server_addr);
if (status != APR_SUCCESS) {
throw BindException(status);
}
status = apr_socket_listen(socket, 50);
if (status != APR_SUCCESS) {
throw SocketException(status);
}
}
ServerSocket::~ServerSocket()
{
}
void ServerSocket::close() {
synchronized sync(mutex);
if (socket != 0) {
apr_status_t status = apr_socket_close(socket);
if (status != APR_SUCCESS) {
throw SocketException(status);
}
socket = 0;
}
}
/** Listens for a connection to be made to this socket and
accepts it
*/
SocketPtr ServerSocket::accept() {
synchronized sync(mutex);
if (socket == 0) {
throw IOException();
}
apr_pollfd_t poll;
poll.p = pool.getAPRPool();
poll.desc_type = APR_POLL_SOCKET;
poll.reqevents = APR_POLLIN;
poll.rtnevents = 0;
poll.desc.s = socket;
poll.client_data = NULL;
apr_int32_t signaled;
apr_interval_time_t to = timeout * 1000;
apr_status_t status = apr_poll(&poll, 1, &signaled, to);
if (APR_STATUS_IS_TIMEUP(status)) {
throw SocketTimeoutException();
} else if (status != APR_SUCCESS) {
throw SocketException(status);
}
apr_pool_t* newPool;
status = apr_pool_create(&newPool, 0);
if (status != APR_SUCCESS) {
throw PoolException(status);
}
apr_socket_t* newSocket;
status = apr_socket_accept(&newSocket, socket, newPool);
if (status != APR_SUCCESS) {
apr_pool_destroy(newPool);
throw SocketException(status);
}
status = apr_socket_opt_set(newSocket, APR_SO_NONBLOCK, 0);
if (status != APR_SUCCESS) {
apr_pool_destroy(newPool);
throw SocketException(status);
}
return new Socket(newSocket, newPool);
}
/** Retrive setting for SO_TIMEOUT.
*/
int ServerSocket::getSoTimeout() const
{
return timeout;
}
/** Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.
*/
void ServerSocket::setSoTimeout(int newVal)
{
timeout = newVal;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/defaultloggerfactory.h>
#include <log4cxx/logger.h>
using namespace log4cxx;
IMPLEMENT_LOG4CXX_OBJECT(DefaultLoggerFactory)
LoggerPtr DefaultLoggerFactory::makeNewLoggerInstance(
log4cxx::helpers::Pool& pool,
const LogString& name) const
{
return new Logger(pool, name);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/charsetencoder.h>
#include <log4cxx/helpers/bytebuffer.h>
#include <log4cxx/helpers/exception.h>
#include <apr_xlate.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/transcoder.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/private/log4cxx_private.h>
#include <apr_portable.h>
#include <log4cxx/helpers/mutex.h>
#include <log4cxx/helpers/synchronized.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(CharsetEncoder)
namespace log4cxx
{
namespace helpers {
#if APR_HAS_XLATE
/**
* A character encoder implemented using apr_xlate.
*/
class APRCharsetEncoder : public CharsetEncoder
{
public:
APRCharsetEncoder(const LogString& topage) : pool(), mutex(pool) {
#if LOG4CXX_LOGCHAR_IS_WCHAR
const char* frompage = "WCHAR_T";
#endif
#if LOG4CXX_LOGCHAR_IS_UTF8
const char* frompage = "UTF-8";
#endif
#if LOG4CXX_LOGCHAR_IS_UNICHAR
const char* frompage = "UTF-16";
#endif
std::string tpage(Transcoder::encodeCharsetName(topage));
apr_status_t stat = apr_xlate_open(&convset,
tpage.c_str(),
frompage,
pool.getAPRPool());
if (stat != APR_SUCCESS) {
throw IllegalArgumentException(topage);
}
}
virtual ~APRCharsetEncoder() {
}
virtual log4cxx_status_t encode(const LogString& in,
LogString::const_iterator& iter,
ByteBuffer& out) {
apr_status_t stat;
size_t outbytes_left = out.remaining();
size_t initial_outbytes_left = outbytes_left;
size_t position = out.position();
if (iter == in.end()) {
synchronized sync(mutex);
stat = apr_xlate_conv_buffer(convset, NULL, NULL,
out.data() + position, &outbytes_left);
} else {
LogString::size_type inOffset = (iter - in.begin());
apr_size_t inbytes_left =
(in.size() - inOffset) * sizeof(LogString::value_type);
apr_size_t initial_inbytes_left = inbytes_left;
{
synchronized sync(mutex);
stat = apr_xlate_conv_buffer(convset,
(const char*) (in.data() + inOffset),
&inbytes_left,
out.data() + position,
&outbytes_left);
}
iter += ((initial_inbytes_left - inbytes_left) / sizeof(LogString::value_type));
}
out.position(out.position() + (initial_outbytes_left - outbytes_left));
return stat;
}
private:
APRCharsetEncoder(const APRCharsetEncoder&);
APRCharsetEncoder& operator=(const APRCharsetEncoder&);
Pool pool;
Mutex mutex;
apr_xlate_t *convset;
};
#endif
#if LOG4CXX_LOGCHAR_IS_WCHAR && LOG4CXX_HAS_WCSTOMBS
/**
* A character encoder implemented using wcstombs.
*/
class WcstombsCharsetEncoder : public CharsetEncoder
{
public:
WcstombsCharsetEncoder() {
}
/**
* Converts a wchar_t to the default external multibyte encoding.
*/
log4cxx_status_t encode(const LogString& in,
LogString::const_iterator& iter,
ByteBuffer& out) {
log4cxx_status_t stat = APR_SUCCESS;
if (iter != in.end()) {
size_t outbytes_left = out.remaining();
size_t position = out.position();
std::wstring::size_type inOffset = (iter - in.begin());
enum { BUFSIZE = 256 };
wchar_t buf[BUFSIZE];
size_t chunkSize = BUFSIZE - 1;
if (chunkSize * MB_LEN_MAX > outbytes_left) {
chunkSize = outbytes_left / MB_LEN_MAX;
}
if (chunkSize > in.length() - inOffset) {
chunkSize = in.length() - inOffset;
}
memset(buf, 0, BUFSIZE * sizeof(wchar_t));
memcpy(buf,
in.data() + inOffset,
chunkSize * sizeof(wchar_t));
size_t converted = wcstombs(out.data() + position, buf, outbytes_left);
if (converted == (size_t) -1) {
stat = APR_BADARG;
//
// if unconvertable character was encountered
// repeatedly halve source to get fragment that
// can be converted
for(chunkSize /= 2;
chunkSize > 0;
chunkSize /= 2) {
buf[chunkSize] = 0;
converted = wcstombs(out.data() + position, buf, outbytes_left);
if (converted != (size_t) -1) {
iter += chunkSize;
out.position(out.position() + converted);
break;
}
}
} else {
iter += chunkSize;
out.position(out.position() + converted);
}
}
return stat;
}
private:
WcstombsCharsetEncoder(const WcstombsCharsetEncoder&);
WcstombsCharsetEncoder& operator=(const WcstombsCharsetEncoder&);
};
#endif
/**
* Encodes a LogString to US-ASCII.
*/
class USASCIICharsetEncoder : public CharsetEncoder
{
public:
USASCIICharsetEncoder() {
}
virtual log4cxx_status_t encode(const LogString& in,
LogString::const_iterator& iter,
ByteBuffer& out) {
log4cxx_status_t stat = APR_SUCCESS;
if (iter != in.end()) {
while(out.remaining() > 0 && iter != in.end()) {
LogString::const_iterator prev(iter);
unsigned int sv = Transcoder::decode(in, iter);
if (sv <= 0x7F) {
out.put((char) sv);
} else {
iter = prev;
stat = APR_BADARG;
break;
}
}
}
return stat;
}
private:
USASCIICharsetEncoder(const USASCIICharsetEncoder&);
USASCIICharsetEncoder& operator=(const USASCIICharsetEncoder&);
};
/**
* Converts a LogString to ISO-8859-1.
*/
class ISOLatinCharsetEncoder : public CharsetEncoder
{
public:
ISOLatinCharsetEncoder() {
}
virtual log4cxx_status_t encode(const LogString& in,
LogString::const_iterator& iter,
ByteBuffer& out) {
log4cxx_status_t stat = APR_SUCCESS;
if (iter != in.end()) {
while(out.remaining() > 0 && iter != in.end()) {
LogString::const_iterator prev(iter);
unsigned int sv = Transcoder::decode(in, iter);
if (sv <= 0xFF) {
out.put((char) sv);
} else {
iter = prev;
stat = APR_BADARG;
break;
}
}
}
return stat;
}
private:
ISOLatinCharsetEncoder(const ISOLatinCharsetEncoder&);
ISOLatinCharsetEncoder& operator=(const ISOLatinCharsetEncoder&);
};
/**
* Encodes a LogString to a byte array when the encodings are identical.
*/
class TrivialCharsetEncoder : public CharsetEncoder
{
public:
TrivialCharsetEncoder() {
}
virtual log4cxx_status_t encode(const LogString& in,
LogString::const_iterator& iter,
ByteBuffer& out) {
if(iter != in.end()) {
size_t requested = in.length() - (iter - in.begin());
if (requested > out.remaining()/sizeof(logchar)) {
requested = out.remaining()/sizeof(logchar);
}
memcpy(out.current(),
(const char*) in.data() + (iter - in.begin()),
requested * sizeof(logchar));
iter += requested;
out.position(out.position() + requested * sizeof(logchar));
}
return APR_SUCCESS;
}
private:
TrivialCharsetEncoder(const TrivialCharsetEncoder&);
TrivialCharsetEncoder& operator=(const TrivialCharsetEncoder&);
};
#if LOG4CXX_LOGCHAR_IS_UTF8
typedef TrivialCharsetEncoder UTF8CharsetEncoder;
#else
/**
* Converts a LogString to UTF-8.
*/
class UTF8CharsetEncoder : public CharsetEncoder {
public:
UTF8CharsetEncoder() {
}
virtual log4cxx_status_t encode(const LogString& in,
LogString::const_iterator& iter,
ByteBuffer& out) {
while(iter != in.end() && out.remaining() >= 8) {
unsigned int sv = Transcoder::decode(in, iter);
if (sv == 0xFFFF) {
return APR_BADARG;
}
Transcoder::encodeUTF8(sv, out);
}
return APR_SUCCESS;
}
private:
UTF8CharsetEncoder(const UTF8CharsetEncoder&);
UTF8CharsetEncoder& operator=(const UTF8CharsetEncoder&);
};
#endif
/**
* Encodes a LogString to UTF16-BE.
*/
class UTF16BECharsetEncoder : public CharsetEncoder {
public:
UTF16BECharsetEncoder() {
}
virtual log4cxx_status_t encode(const LogString& in,
LogString::const_iterator& iter,
ByteBuffer& out) {
while(iter != in.end() && out.remaining() >= 4) {
unsigned int sv = Transcoder::decode(in, iter);
if (sv == 0xFFFF) {
return APR_BADARG;
}
Transcoder::encodeUTF16BE(sv, out);
}
return APR_SUCCESS;
}
private:
UTF16BECharsetEncoder(const UTF16BECharsetEncoder&);
UTF16BECharsetEncoder& operator=(const UTF16BECharsetEncoder&);
};
/**
* Encodes a LogString to UTF16-LE.
*/
class UTF16LECharsetEncoder : public CharsetEncoder {
public:
UTF16LECharsetEncoder() {
}
virtual log4cxx_status_t encode(const LogString& in,
LogString::const_iterator& iter,
ByteBuffer& out) {
while(iter != in.end() && out.remaining() >= 4) {
unsigned int sv = Transcoder::decode(in, iter);
if (sv == 0xFFFF) {
return APR_BADARG;
}
Transcoder::encodeUTF16LE(sv, out);
}
return APR_SUCCESS;
}
private:
UTF16LECharsetEncoder(const UTF16LECharsetEncoder&);
UTF16LECharsetEncoder& operator=(const UTF16LECharsetEncoder&);
};
/**
* Charset encoder that uses an embedded CharsetEncoder consistent
* with current locale settings.
*/
class LocaleCharsetEncoder : public CharsetEncoder {
public:
LocaleCharsetEncoder() : pool(), mutex(pool), encoder(), encoding() {
}
virtual ~LocaleCharsetEncoder() {
}
virtual log4cxx_status_t encode(const LogString& in,
LogString::const_iterator& iter,
ByteBuffer& out) {
#if !LOG4CXX_CHARSET_EBCDIC
char* current = out.current();
size_t remain = out.remaining();
for(;
iter != in.end() && ((unsigned int) *iter) < 0x80 && remain > 0;
iter++, remain--, current++) {
*current = *iter;
}
out.position(current - out.data());
#endif
if (iter != in.end() && out.remaining() > 0) {
Pool subpool;
const char* enc = apr_os_locale_encoding(subpool.getAPRPool());
{
synchronized sync(mutex);
if (enc == 0) {
if (encoder == 0) {
encoding = "C";
encoder = new USASCIICharsetEncoder();
}
} else if (encoding != enc) {
encoding = enc;
LogString ename;
Transcoder::decode(encoding, ename);
try {
encoder = CharsetEncoder::getEncoder(ename);
} catch(IllegalArgumentException ex) {
encoder = new USASCIICharsetEncoder();
}
}
}
return encoder->encode(in, iter, out);
}
return APR_SUCCESS;
}
private:
LocaleCharsetEncoder(const LocaleCharsetEncoder&);
LocaleCharsetEncoder& operator=(const LocaleCharsetEncoder&);
Pool pool;
Mutex mutex;
CharsetEncoderPtr encoder;
std::string encoding;
};
} // namespace helpers
} //namespace log4cxx
CharsetEncoder::CharsetEncoder() {
}
CharsetEncoder::~CharsetEncoder() {
}
CharsetEncoderPtr CharsetEncoder::getDefaultEncoder() {
static CharsetEncoderPtr encoder(createDefaultEncoder());
//
// if invoked after static variable destruction
// (if logging is called in the destructor of a static object)
// then create a new decoder.
//
if (encoder == 0) {
return createDefaultEncoder();
}
return encoder;
}
CharsetEncoder* CharsetEncoder::createDefaultEncoder() {
#if LOG4CXX_CHARSET_UTF8
return new UTF8CharsetEncoder();
#elif LOG4CXX_CHARSET_ISO88591
return new ISOLatinCharsetEncoder();
#elif LOG4CXX_CHARSET_USASCII
return new USASCIICharsetEncoder();
#elif LOG4CXX_LOGCHAR_IS_WCHAR && LOG4CXX_HAS_WCSTOMBS
return new WcstombsCharsetEncoder();
#else
return new LocaleCharsetEncoder();
#endif
}
CharsetEncoderPtr CharsetEncoder::getUTF8Encoder() {
return new UTF8CharsetEncoder();
}
CharsetEncoderPtr CharsetEncoder::getEncoder(const LogString& charset) {
if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("UTF-8"), LOG4CXX_STR("utf-8"))) {
return new UTF8CharsetEncoder();
} else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("C"), LOG4CXX_STR("c")) ||
charset == LOG4CXX_STR("646") ||
StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("US-ASCII"), LOG4CXX_STR("us-ascii")) ||
StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ISO646-US"), LOG4CXX_STR("iso646-US")) ||
StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ANSI_X3.4-1968"), LOG4CXX_STR("ansi_x3.4-1968"))) {
return new USASCIICharsetEncoder();
} else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ISO-8859-1"), LOG4CXX_STR("iso-8859-1")) ||
StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ISO-LATIN-1"), LOG4CXX_STR("iso-latin-1"))) {
return new ISOLatinCharsetEncoder();
} else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("UTF-16BE"), LOG4CXX_STR("utf-16be"))
|| StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("UTF-16"), LOG4CXX_STR("utf-16"))) {
return new UTF16BECharsetEncoder();
} else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("UTF-16LE"), LOG4CXX_STR("utf-16le"))) {
return new UTF16LECharsetEncoder();
}
#if APR_HAS_XLATE || !defined(_WIN32)
return new APRCharsetEncoder(charset);
#else
throw IllegalArgumentException(charset);
#endif
}
void CharsetEncoder::reset() {
}
void CharsetEncoder::flush(ByteBuffer& /* out */ ) {
}
void CharsetEncoder::encode(CharsetEncoderPtr& enc,
const LogString& src,
LogString::const_iterator& iter,
ByteBuffer& dst) {
log4cxx_status_t stat = enc->encode(src, iter, dst);
if (stat != APR_SUCCESS && iter != src.end()) {
#if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR
iter++;
#elif LOG4CXX_LOGCHAR_IS_UTF8
// advance past this character and all continuation characters
while((*(++iter) & 0xC0) == 0x80);
#else
#error logchar is unrecognized
#endif
dst.put(Transcoder::LOSSCHAR);
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/bytearrayinputstream.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/helpers/bytebuffer.h>
#include <apr_file_io.h>
#include <log4cxx/helpers/transcoder.h>
#include <algorithm>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace std;
IMPLEMENT_LOG4CXX_OBJECT(ByteArrayInputStream)
ByteArrayInputStream::ByteArrayInputStream(const std::vector<unsigned char>& bytes) :
buf(bytes), pos(0) {
}
ByteArrayInputStream::~ByteArrayInputStream() {
}
void ByteArrayInputStream::close() {
}
int ByteArrayInputStream::read(ByteBuffer& dst) {
if (pos >= buf.size()) {
return -1;
} else {
size_t bytesCopied = min(dst.remaining(), buf.size() - pos);
memcpy(dst.current(), &buf[pos], bytesCopied);
pos += bytesCopied;
dst.position(dst.position() + bytesCopied);
return bytesCopied;
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/pattern/integerpatternconverter.h>
#include <log4cxx/helpers/integer.h>
#include <log4cxx/helpers/stringhelper.h>
using namespace log4cxx;
using namespace log4cxx::pattern;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(IntegerPatternConverter)
IntegerPatternConverter::IntegerPatternConverter() :
PatternConverter(LOG4CXX_STR("Integer"),
LOG4CXX_STR("integer")) {
}
PatternConverterPtr IntegerPatternConverter::newInstance(
const std::vector<LogString>& /* options */) {
static PatternConverterPtr instance(new IntegerPatternConverter());
return instance;
}
void IntegerPatternConverter::format(
const ObjectPtr& obj,
LogString& toAppendTo,
Pool& p) const {
IntegerPtr i(obj);
if (i != NULL) {
StringHelper::toString(i->intValue(), p, toAppendTo);
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/datagrampacket.h>
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(DatagramPacket)
/** Constructs a DatagramPacket for receiving packets of length
<code>length</code>. */
DatagramPacket::DatagramPacket(void * buf1, int length1)
: buf(buf1), offset(0), length(length1), address(), port(0)
{
}
/** Constructs a datagram packet for sending packets of length
<code>length/<code> to the specified port number on the specified
host. */
DatagramPacket::DatagramPacket(void * buf1, int length1, InetAddressPtr address1,
int port1)
: buf(buf1), offset(0), length(length1), address(address1), port(port1)
{
}
/** Constructs a DatagramPacket for receiving packets of length
<code>length</code>, specifying an offset into the buffer. */
DatagramPacket::DatagramPacket(void * buf1, int offset1, int length1)
: buf(buf1), offset(offset1), length(length1), address(), port(0)
{
}
/** Constructs a datagram packet for sending packets of length
<code>length</code> with offset <code>offset</code> to the
specified port number on the specified host. */
DatagramPacket::DatagramPacket(void * buf1, int offset1, int length1,
InetAddressPtr address1, int port1)
: buf(buf1), offset(offset1), length(length1), address(address1), port(port1)
{
}
DatagramPacket::~DatagramPacket()
{
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/loader.h>
#include <log4cxx/appender.h>
#include <log4cxx/spi/filter.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/spi/loggerfactory.h>
#include <log4cxx/spi/loggerrepository.h>
#include <log4cxx/helpers/object.h>
#include <log4cxx/spi/errorhandler.h>
#include <log4cxx/filter/denyallfilter.h>
#include <log4cxx/spi/repositoryselector.h>
#include <log4cxx/spi/appenderattachable.h>
#include <log4cxx/helpers/xml.h>
#include <log4cxx/spi/triggeringeventevaluator.h>
#include <fstream>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/helpers/fileinputstream.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
using namespace log4cxx::filter;
IMPLEMENT_LOG4CXX_OBJECT(Object)
IMPLEMENT_LOG4CXX_OBJECT(OptionHandler)
IMPLEMENT_LOG4CXX_OBJECT(ErrorHandler)
IMPLEMENT_LOG4CXX_OBJECT(Appender)
IMPLEMENT_LOG4CXX_OBJECT(Filter)
IMPLEMENT_LOG4CXX_OBJECT(AppenderAttachable)
IMPLEMENT_LOG4CXX_OBJECT(LoggerFactory)
IMPLEMENT_LOG4CXX_OBJECT(LoggerRepository)
IMPLEMENT_LOG4CXX_OBJECT(DenyAllFilter)
IMPLEMENT_LOG4CXX_OBJECT(RepositorySelector)
IMPLEMENT_LOG4CXX_OBJECT(XMLDOMNode)
IMPLEMENT_LOG4CXX_OBJECT(XMLDOMDocument)
IMPLEMENT_LOG4CXX_OBJECT(XMLDOMElement)
IMPLEMENT_LOG4CXX_OBJECT(XMLDOMNodeList)
IMPLEMENT_LOG4CXX_OBJECT(TriggeringEventEvaluator)
const Class& Loader::loadClass(const LogString& clazz)
{
return Class::forName(clazz);
}
InputStreamPtr Loader::getResourceAsStream(const LogString& name) {
try {
return new FileInputStream(name);
} catch(const IOException& ioex) {
}
return 0;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/net/socketappender.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/helpers/synchronized.h>
#include <log4cxx/helpers/objectoutputstream.h>
#include <apr_time.h>
#include <apr_atomic.h>
#include <apr_thread_proc.h>
#include <log4cxx/helpers/socketoutputstream.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::net;
IMPLEMENT_LOG4CXX_OBJECT(SocketAppender)
// The default port number of remote logging server (4560)
int SocketAppender::DEFAULT_PORT = 4560;
// The default reconnection delay (30000 milliseconds or 30 seconds).
int SocketAppender::DEFAULT_RECONNECTION_DELAY = 30000;
SocketAppender::SocketAppender()
: SocketAppenderSkeleton(DEFAULT_PORT, DEFAULT_RECONNECTION_DELAY) {
}
SocketAppender::SocketAppender(InetAddressPtr& address1, int port1)
: SocketAppenderSkeleton(address1, port1, DEFAULT_RECONNECTION_DELAY) {
Pool p;
activateOptions(p);
}
SocketAppender::SocketAppender(const LogString& host, int port1)
: SocketAppenderSkeleton(host, port1, DEFAULT_RECONNECTION_DELAY) {
Pool p;
activateOptions(p);
}
SocketAppender::~SocketAppender()
{
finalize();
}
int SocketAppender::getDefaultDelay() const {
return DEFAULT_RECONNECTION_DELAY;
}
int SocketAppender::getDefaultPort() const {
return DEFAULT_PORT;
}
void SocketAppender::setSocket(log4cxx::helpers::SocketPtr& socket, Pool& p) {
synchronized sync(mutex);
oos = new ObjectOutputStream(new SocketOutputStream(socket), p);
}
void SocketAppender::cleanUp(Pool& p) {
if (oos != 0) {
try {
oos->close(p);
oos = 0;
} catch(std::exception& e) {
}
}
}
void SocketAppender::append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) {
if (oos != 0) {
LogString ndcVal;
event->getNDC(ndcVal);
event->getThreadName();
// Get a copy of this thread's MDC.
event->getMDCCopy();
try {
event->write(*oos, p);
oos->flush(p);
} catch(std::exception& e) {
oos = 0;
LogLog::warn(LOG4CXX_STR("Detected problem with connection: "), e);
if (getReconnectionDelay() > 0) {
fireConnector();
}
}
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/helpers/pool.h>
#include <stdlib.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/helpers/bytebuffer.h>
#include <log4cxx/helpers/charsetdecoder.h>
#include <log4cxx/helpers/charsetencoder.h>
#include <vector>
#include <apr.h>
#include <apr_strings.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/private/log4cxx_private.h>
#if LOG4CXX_LOGCHAR_IS_UNICHAR || LOG4CXX_CFSTRING_API || LOG4CXX_UNICHAR_API
#include <CoreFoundation/CFString.h>
#endif
using namespace log4cxx;
using namespace log4cxx::helpers;
void Transcoder::decodeUTF8(const std::string& src, LogString& dst) {
std::string::const_iterator iter = src.begin();
while(iter != src.end()) {
unsigned int sv = decode(src, iter);
if(sv != 0xFFFF) {
encode(sv, dst);
} else {
dst.append(1, LOSSCHAR);
iter++;
}
}
}
void Transcoder::encodeUTF8(const LogString& src, std::string& dst) {
#if LOG4CXX_LOGCHAR_IS_UTF8
dst.append(src);
#else
LogString::const_iterator iter = src.begin();
while(iter != src.end()) {
unsigned int sv = decode(src, iter);
if(sv != 0xFFFF) {
encode(sv, dst);
} else {
dst.append(1, LOSSCHAR);
iter++;
}
}
#endif
}
char* Transcoder::encodeUTF8(const LogString& src, Pool& p) {
#if LOG4CXX_LOGCHAR_IS_UTF8
return p.pstrdup(src);
#else
std::string tmp;
encodeUTF8(src, tmp);
return p.pstrdup(tmp);
#endif
}
void Transcoder::encodeUTF8(unsigned int sv, ByteBuffer& dst) {
size_t bytes = encodeUTF8(sv, dst.current());
dst.position(dst.position() + bytes);
}
size_t Transcoder::encodeUTF8(unsigned int ch, char* dst) {
if (ch < 0x80) {
dst[0] = (char) ch;
return 1;
} else if (ch < 0x800) {
dst[0] = (char) (0xC0 + (ch >> 6));
dst[1] = (char) (0x80 + (ch & 0x3F));
return 2;
} else if (ch < 0x10000) {
dst[0] = (char) (0xE0 + (ch >> 12));
dst[1] = (char) (0x80 + ((ch >> 6) & 0x3F));
dst[2] = (char) (0x80 + (ch & 0x3F));
return 3;
} else if (ch <= 0x10FFFF) {
dst[0] = (char) (0xF0 + (ch >> 18));
dst[1] = (char) (0x80 + ((ch >> 12) & 0x3F));
dst[2] = (char) (0x80 + ((ch >> 6) & 0x3F));
dst[3] = (char) (0x80 + (ch & 0x3F));
return 4;
} else {
//
// output UTF-8 encoding of 0xFFFF
//
dst[0] = (char) 0xEF;
dst[1] = (char) 0xBF;
dst[2] = (char) 0xBF;
return 3;
}
}
void Transcoder::encodeUTF16BE(unsigned int sv, ByteBuffer& dst) {
size_t bytes = encodeUTF16BE(sv, dst.current());
dst.position(dst.position() + bytes);
}
size_t Transcoder::encodeUTF16BE(unsigned int ch, char* dst) {
if (ch <= 0xFFFF) {
dst[0] = (char) (ch >> 8);
dst[1] = (char) (ch & 0xFF);
return 2;
}
if (ch <= 0x10FFFF) {
unsigned char w = (unsigned char) ((ch >> 16) - 1);
dst[0] = (char) (0xD8 + (w >> 2));
dst[1] = (char) (((w & 0x03) << 6) + ((ch >> 10) & 0x3F));
dst[2] = (char) (0xDC + ((ch & 0x30) >> 4));
dst[3] = (char) (ch & 0xFF);
return 4;
}
dst[0] = dst[1] = (char) 0xFF;
return 2;
}
void Transcoder::encodeUTF16LE(unsigned int sv, ByteBuffer& dst) {
size_t bytes = encodeUTF16LE(sv, dst.current());
dst.position(dst.position() + bytes);
}
size_t Transcoder::encodeUTF16LE(unsigned int ch, char* dst) {
if (ch <= 0xFFFF) {
dst[1] = (char) (ch >> 8);
dst[0] = (char) (ch & 0xFF);
return 2;
}
if (ch <= 0x10FFFF) {
unsigned char w = (unsigned char) ((ch >> 16) - 1);
dst[1] = (char) (0xD8 + (w >> 2));
dst[0] = (char) (((w & 0x03) << 6) + ((ch >> 10) & 0x3F));
dst[3] = (char) (0xDC + ((ch & 0x30) >> 4));
dst[2] = (char) (ch & 0xFF);
return 4;
}
dst[0] = dst[1] = (char) 0xFF;
return 2;
}
unsigned int Transcoder::decode(const std::string& src,
std::string::const_iterator& iter) {
std::string::const_iterator start(iter);
unsigned char ch1 = *(iter++);
if (ch1 <= 0x7F) {
return ch1;
}
//
// should not have continuation character here
//
if ((ch1 & 0xC0) != 0x80 && iter != src.end()) {
unsigned char ch2 = *(iter++);
//
// should be continuation
if ((ch2 & 0xC0) != 0x80) {
iter = start;
return 0xFFFF;
}
if((ch1 & 0xE0) == 0xC0) {
if ((ch2 & 0xC0) == 0x80) {
unsigned int rv = ((ch1 & 0x1F) << 6) + (ch2 & 0x3F);
if (rv >= 0x80) {
return rv;
}
}
iter = start;
return 0xFFFF;
}
if (iter != src.end()) {
unsigned char ch3 = *(iter++);
//
// should be continuation
//
if ((ch3 & 0xC0) != 0x80) {
iter = start;
return 0xFFFF;
}
if ((ch1 & 0xF0) == 0xE0) {
unsigned rv = ((ch1 & 0x0F) << 12)
+ ((ch2 & 0x3F) << 6)
+ (ch3 & 0x3F);
if (rv <= 0x800) {
iter = start;
return 0xFFFF;
}
return rv;
}
if (iter != src.end()) {
unsigned char ch4 = *(iter++);
if ((ch4 & 0xC0) != 0x80) {
iter = start;
return 0xFFFF;
}
unsigned int rv = ((ch1 & 0x07) << 18)
+ ((ch2 & 0x3F) << 12)
+ ((ch3 & 0x3F) << 6)
+ (ch4 & 0x3F);
if (rv > 0xFFFF) {
return rv;
}
}
}
}
iter = start;
return 0xFFFF;
}
void Transcoder::encode(unsigned int sv, std::string& dst) {
char tmp[8];
size_t bytes = encodeUTF8(sv, tmp);
dst.append(tmp, bytes);
}
void Transcoder::decode(const std::string& src, LogString& dst) {
#if LOG4CXX_CHARSET_UTF8 && LOG4CXX_LOGCHAR_IS_UTF8
dst.append(src);
#else
static CharsetDecoderPtr decoder(CharsetDecoder::getDefaultDecoder());
dst.reserve(dst.size() + src.size());
std::string::const_iterator iter = src.begin();
#if !LOG4CXX_CHARSET_EBCDIC
for(;
iter != src.end() && ((unsigned char) *iter) < 0x80;
iter++) {
dst.append(1, *iter);
}
#endif
if (iter != src.end()) {
size_t offset = iter - src.begin();
ByteBuffer buf(const_cast<char*>(src.data() + offset), src.size() - offset);
while(buf.remaining() > 0) {
log4cxx_status_t stat = decoder->decode(buf, dst);
if(CharsetDecoder::isError(stat)) {
dst.append(1, LOSSCHAR);
buf.position(buf.position() + 1);
}
}
decoder->decode(buf, dst);
}
#endif
}
char* Transcoder::encode(const LogString& src, Pool& p) {
#if LOG4CXX_CHARSET_UTF8 && LOG4CXX_LOGCHAR_IS_UTF8
return p.pstrdup(src);
#else
std::string tmp;
encode(src, tmp);
return p.pstrdup(tmp);
#endif
}
void Transcoder::encode(const LogString& src, std::string& dst) {
#if LOG4CXX_CHARSET_UTF8 && LOG4CXX_LOGCHAR_IS_UTF8
dst.append(src);
#else
static CharsetEncoderPtr encoder(CharsetEncoder::getDefaultEncoder());
dst.reserve(dst.size() + src.size());
LogString::const_iterator iter = src.begin();
#if !LOG4CXX_CHARSET_EBCDIC
for(;
iter != src.end() && ((unsigned int) *iter) < 0x80;
iter++) {
dst.append(1, *iter);
}
#endif
if (iter != src.end()) {
char buf[BUFSIZE];
ByteBuffer out(buf, BUFSIZE);
while(iter != src.end()) {
log4cxx_status_t stat = encoder->encode(src, iter, out);
out.flip();
dst.append(out.data(), out.limit());
out.clear();
if (CharsetEncoder::isError(stat)) {
dst.append(1, LOSSCHAR);
iter++;
}
}
encoder->encode(src, iter, out);
}
#endif
}
template<class String, class Iterator>
static unsigned int decodeUTF16(const String& in, Iterator& iter) {
unsigned int ch1 = *iter;
//
// if not surrogate pair
//
if (ch1 < 0xD800 || ch1 > 0xDFFF) {
//
// then advance iterator and return wchar_t value
//
if(ch1 != 0xFFFF) iter++;
return ch1;
} else if (ch1 < 0xDC00) {
//
// started with high-surrogate value
// if there is an additional wchar_t
Iterator iter2 = iter + 1;
if (iter2 != in.end()) {
unsigned int ch2 = *iter2;
//
// if it is a matching low surrogate then
// advance the iterator and return the scalar value
if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
iter += 2;
return (ch1 - 0xD800) * 0x400 + (ch2 - 0xDC00) + 0x10000;
}
}
}
//
// unrecognized value, do not advance iterator
//
return 0xFFFF;
}
template<class String>
static void encodeUTF16(unsigned int sv, String& dst) {
if (sv < 0x10000) {
dst.append(1, sv);
} else {
unsigned char u = (unsigned char) (sv >> 16);
unsigned char w = (unsigned char) (u - 1);
unsigned short hs = (0xD800 + ((w & 0xF) << 6) + ((sv & 0xFFFF) >> 10));
unsigned short ls = (0xDC00 + (sv && 0x3FF));
dst.append(1, hs);
dst.append(1, ls);
}
}
#if LOG4CXX_WCHAR_T_API || LOG4CXX_LOGCHAR_IS_WCHAR_T || defined(WIN32) || defined(_WIN32)
void Transcoder::decode(const std::wstring& src, LogString& dst) {
#if LOG4CXX_LOGCHAR_IS_WCHAR_T
dst.append(src, len);
#else
std::wstring::const_iterator i = src.begin();
while(i != src.end()) {
unsigned int cp = decode(src, i);
if (cp != 0xFFFF) {
encode(cp, dst);
} else {
dst.append(1, LOSSCHAR);
i++;
}
}
#endif
}
void Transcoder::encode(const LogString& src, std::wstring& dst) {
#if LOG4CXX_LOGCHAR_IS_WCHAR_T
dst.append(src);
#else
for(LogString::const_iterator i = src.begin();
i != src.end();) {
unsigned int cp = Transcoder::decode(src, i);
encode(cp, dst);
}
#endif
}
wchar_t* Transcoder::wencode(const LogString& src, Pool& p) {
#if LOG4CXX_LOGCHAR_IS_WCHAR_T
std::wstring& tmp = src;
#else
std::wstring tmp;
encode(src, tmp);
#endif
wchar_t* dst = (wchar_t*) p.palloc((tmp.length() + 1) * sizeof(wchar_t));
dst[tmp.length()] = 0;
memcpy(dst, tmp.data(), tmp.length() * sizeof(wchar_t));
return dst;
}
unsigned int Transcoder::decode(const std::wstring& in,
std::wstring::const_iterator& iter) {
#if defined(__STDC_ISO_10646__)
return *(iter++);
#else
return decodeUTF16(in, iter);
#endif
}
void Transcoder::encode(unsigned int sv, std::wstring& dst) {
#if defined(__STDC_ISO_10646__)
dst.append(1, sv);
#else
if (sizeof(wchar_t) == 4) {
dst.append(1, sv);
} else {
encodeUTF16(sv, dst);
}
#endif
}
#endif
#if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API
void Transcoder::decode(const std::basic_string<UniChar>& src, LogString& dst) {
#if LOG4CXX_LOGCHAR_IS_UNICHAR
dst.append(src);
#else
for(std::basic_string<UniChar>::const_iterator i = src.begin();
i != src.end();) {
unsigned int cp = decode(src, i);
encode(cp, dst);
}
#endif
}
void Transcoder::encode(const LogString& src, std::basic_string<UniChar>& dst) {
#if LOG4CXX_LOGCHAR_IS_UNICHAR
dst.append(src);
#else
for(LogString::const_iterator i = src.begin();
i != src.end();) {
unsigned int cp = decode(src, i);
encode(cp, dst);
}
#endif
}
unsigned int Transcoder::decode(const std::basic_string<UniChar>& in,
std::basic_string<UniChar>::const_iterator& iter) {
return decodeUTF16(in, iter);
}
void Transcoder::encode(unsigned int sv, std::basic_string<UniChar>& dst) {
encodeUTF16(sv, dst);
}
#endif
#if LOG4CXX_CFSTRING_API
void Transcoder::decode(const CFStringRef& src, LogString& dst) {
const UniChar* chars = CFStringGetCharactersPtr(src);
if (chars) {
decode(chars, dst);
} else {
size_t length = CFStringGetLength(src);
if (length > 0) {
std::vector<UniChar> tmp(length);
CFStringGetCharacters(src, CFRangeMake(0, length), &tmp[0]);
#if LOG4CXX_LOGCHAR_IS_UNICHAR
dst.append(&tmp[0], tmp.size());
#else
decode(std::basic_string<UniChar>(&tmp[0], tmp.size()), dst);
#endif
}
}
}
CFStringRef Transcoder::encode(const LogString& src) {
LOG4CXX_ENCODE_UNICHAR(tmp, src);
return CFStringCreateWithCharacters(kCFAllocatorDefault, tmp.data(), tmp.size());
}
#endif
logchar Transcoder::decode(char val) {
#if LOG4CXX_CHARSET_EBCDIC
LogString dst;
Transcoder::decode(std::string(1, val), dst);
return dst[0];
#else
return val;
#endif
}
LogString Transcoder::decode(const char* val) {
#if LOG4CXX_LOGCHAR_IS_UTF8 && !LOG4CXX_CHARSET_EBCDIC
return val;
#else
LogString dst;
Transcoder::decode(val, dst);
return dst;
#endif
}
std::string Transcoder::encodeCharsetName(const LogString& val) {
char asciiTable[] = { ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/',
'0', '1', '2', '3', '4', '5', '6' , '7', '8', '9', ':', ';', '<', '=', '>', '?',
'@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
'`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', ' ' };
std::string out;
for(LogString::const_iterator iter = val.begin();
iter != val.end();
iter++) {
if (*iter >= 0x30 && *iter < 0x7F) {
out.append(1, asciiTable[*iter - 0x30]);
} else {
out.append(1, LOSSCHAR);
}
}
return out;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/spi/filter.h>
using namespace log4cxx;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
Filter::Filter() : next() {
}
void Filter::addRef() const {
ObjectImpl::addRef();
}
void Filter::releaseRef() const {
ObjectImpl::releaseRef();
}
FilterPtr Filter::getNext() const {
return next;
}
void Filter::setNext(const FilterPtr& newNext) {
next = newNext;
}
void Filter::activateOptions(Pool&) {
}
void Filter::setOption(const LogString&, const LogString&) {
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/reader.h>
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(Reader)
Reader::Reader() {
}
Reader::~Reader() {
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/pattern/patternparser.h>
#include <log4cxx/pattern/loggingeventpatternconverter.h>
#include <log4cxx/pattern/formattinginfo.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/pattern/loggerpatternconverter.h>
#include <log4cxx/pattern/literalpatternconverter.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/pattern/classnamepatternconverter.h>
#include <log4cxx/pattern/datepatternconverter.h>
#include <log4cxx/pattern/filedatepatternconverter.h>
#include <log4cxx/pattern/filelocationpatternconverter.h>
#include <log4cxx/pattern/fulllocationpatternconverter.h>
#include <log4cxx/pattern/integerpatternconverter.h>
#include <log4cxx/pattern/linelocationpatternconverter.h>
#include <log4cxx/pattern/messagepatternconverter.h>
#include <log4cxx/pattern/lineseparatorpatternconverter.h>
#include <log4cxx/pattern/methodlocationpatternconverter.h>
#include <log4cxx/pattern/levelpatternconverter.h>
#include <log4cxx/pattern/relativetimepatternconverter.h>
#include <log4cxx/pattern/threadpatternconverter.h>
#include <log4cxx/pattern/ndcpatternconverter.h>
#include <log4cxx/pattern/propertiespatternconverter.h>
#include <log4cxx/pattern/throwableinformationpatternconverter.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
using namespace log4cxx::pattern;
IMPLEMENT_LOG4CXX_OBJECT(PatternLayout)
PatternLayout::PatternLayout()
{
}
/**
Constructs a PatternLayout using the supplied conversion pattern.
*/
PatternLayout::PatternLayout(const LogString& pattern)
: conversionPattern(pattern) {
Pool pool;
activateOptions(pool);
}
void PatternLayout::setConversionPattern(const LogString& pattern)
{
conversionPattern = pattern;
Pool pool;
activateOptions(pool);
}
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 PatternLayout::setOption(const LogString& option, const LogString& value)
{
if (StringHelper::equalsIgnoreCase(option,
LOG4CXX_STR("CONVERSIONPATTERN"),
LOG4CXX_STR("conversionpattern")))
{
conversionPattern = OptionConverter::convertSpecialChars(value);
}
}
void PatternLayout::activateOptions(Pool&)
{
LogString pat(conversionPattern);
if (pat.empty()) {
pat = LOG4CXX_STR("%m%n");
}
patternConverters.erase(patternConverters.begin(), patternConverters.end());
patternFields.erase(patternFields.begin(), patternFields.end());
std::vector<PatternConverterPtr> converters;
PatternParser::parse(pat,
converters,
patternFields,
getFormatSpecifiers());
//
// strip out any pattern converters that don't handle LoggingEvents
//
//
for(std::vector<PatternConverterPtr>::const_iterator converterIter = converters.begin();
converterIter != converters.end();
converterIter++) {
LoggingEventPatternConverterPtr eventConverter(*converterIter);
if (eventConverter != NULL) {
patternConverters.push_back(eventConverter);
}
}
}
#define RULES_PUT(spec, cls) \
specs.insert(PatternMap::value_type(LogString(LOG4CXX_STR(spec)), (PatternConstructor) cls ::newInstance))
log4cxx::pattern::PatternMap PatternLayout::getFormatSpecifiers() {
PatternMap specs;
RULES_PUT("c", LoggerPatternConverter);
RULES_PUT("logger", LoggerPatternConverter);
RULES_PUT("C", ClassNamePatternConverter);
RULES_PUT("class", ClassNamePatternConverter);
RULES_PUT("d", DatePatternConverter);
RULES_PUT("date", DatePatternConverter);
RULES_PUT("F", FileLocationPatternConverter);
RULES_PUT("file", FileLocationPatternConverter);
RULES_PUT("l", FullLocationPatternConverter);
RULES_PUT("L", LineLocationPatternConverter);
RULES_PUT("line", LineLocationPatternConverter);
RULES_PUT("m", MessagePatternConverter);
RULES_PUT("message", MessagePatternConverter);
RULES_PUT("n", LineSeparatorPatternConverter);
RULES_PUT("M", MethodLocationPatternConverter);
RULES_PUT("method", MethodLocationPatternConverter);
RULES_PUT("p", LevelPatternConverter);
RULES_PUT("level", LevelPatternConverter);
RULES_PUT("r", RelativeTimePatternConverter);
RULES_PUT("relative", RelativeTimePatternConverter);
RULES_PUT("t", ThreadPatternConverter);
RULES_PUT("thread", ThreadPatternConverter);
RULES_PUT("x", NDCPatternConverter);
RULES_PUT("ndc", NDCPatternConverter);
RULES_PUT("X", PropertiesPatternConverter);
RULES_PUT("properties", PropertiesPatternConverter);
RULES_PUT("throwable", ThrowableInformationPatternConverter);
return specs;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/db/odbcappender.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/patternlayout.h>
#include <apr_strings.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/private/log4cxx_private.h>
#if LOG4CXX_HAVE_ODBC
#if defined(WIN32) || defined(_WIN32)
#include <windows.h>
#endif
#include <sqlext.h>
#endif
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::db;
using namespace log4cxx::spi;
SQLException::SQLException(short fHandleType,
void* hInput, const char* prolog,
log4cxx::helpers::Pool& p)
: Exception(formatMessage(fHandleType, hInput, prolog, p)) {
}
SQLException::SQLException(const char* msg)
: Exception(msg) {
}
SQLException::SQLException(const SQLException& src)
: Exception(src) {
}
const char* SQLException::formatMessage(short fHandleType,
void* hInput, const char* prolog, log4cxx::helpers::Pool& p) {
std::string strReturn(prolog);
strReturn.append(" - ");
#if LOG4CXX_HAVE_ODBC
SQLCHAR SqlState[6];
SQLCHAR Msg[SQL_MAX_MESSAGE_LENGTH];
SQLINTEGER NativeError;
SQLSMALLINT i;
SQLSMALLINT MsgLen;
SQLRETURN rc2;
// Get the status records.
i = 1;
while ((rc2 = SQLGetDiagRecA(fHandleType, hInput, i, SqlState, &NativeError,
Msg, sizeof(Msg), &MsgLen)) != SQL_NO_DATA)
{
strReturn.append((char*) Msg);
i++;
}
#else
strReturn.append("log4cxx built without ODBC support");
#endif
return apr_pstrdup((apr_pool_t*) p.getAPRPool(), strReturn.c_str());
}
IMPLEMENT_LOG4CXX_OBJECT(ODBCAppender)
ODBCAppender::ODBCAppender()
: connection(0), env(0), bufferSize(1)
{
}
ODBCAppender::~ODBCAppender()
{
finalize();
}
void ODBCAppender::setOption(const LogString& option, const LogString& value)
{
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFERSIZE"), LOG4CXX_STR("buffersize")))
{
setBufferSize((size_t)OptionConverter::toInt(value, 1));
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("PASSWORD"), LOG4CXX_STR("password")))
{
setPassword(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SQL"), LOG4CXX_STR("sql")))
{
setSql(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("URL"), LOG4CXX_STR("url"))
|| StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("DSN"), LOG4CXX_STR("dsn"))
|| StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("CONNECTIONSTRING"), LOG4CXX_STR("connectionstring")) )
{
setURL(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("USER"), LOG4CXX_STR("user")))
{
setUser(value);
}
else
{
AppenderSkeleton::setOption(option, value);
}
}
void ODBCAppender::activateOptions(log4cxx::helpers::Pool&) {
#if !LOG4CXX_HAVE_ODBC
LogLog::error(LOG4CXX_STR("Can not activate ODBCAppender unless compiled with ODBC support."));
#endif
}
void ODBCAppender::append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p)
{
#if LOG4CXX_HAVE_ODBC
buffer.push_back(event);
if (buffer.size() >= bufferSize)
flushBuffer(p);
#endif
}
LogString ODBCAppender::getLogStatement(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) const
{
LogString sbuf;
getLayout()->format(sbuf, event, p);
return sbuf;
}
void ODBCAppender::execute(const LogString& sql, log4cxx::helpers::Pool& p)
{
#if LOG4CXX_HAVE_ODBC
SQLRETURN ret;
SQLHDBC con = SQL_NULL_HDBC;
SQLHSTMT stmt = SQL_NULL_HSTMT;
try
{
con = getConnection(p);
ret = SQLAllocHandle( SQL_HANDLE_STMT, con, &stmt);
if (ret < 0)
{
throw SQLException( SQL_HANDLE_DBC, con, "Failed to allocate sql handle.", p);
}
SQLWCHAR* wsql = Transcoder::wencode(sql, p);
ret = SQLExecDirectW(stmt, wsql, SQL_NTS);
if (ret < 0)
{
throw SQLException(SQL_HANDLE_STMT, stmt, "Failed to execute sql statement.", p);
}
}
catch (SQLException& e)
{
if (stmt != SQL_NULL_HSTMT)
{
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
}
throw e;
}
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
closeConnection(con);
#else
throw SQLException("log4cxx build without ODBC support");
#endif
}
/* The default behavior holds a single connection open until the appender
is closed (typically when garbage collected).*/
void ODBCAppender::closeConnection(ODBCAppender::SQLHDBC /* con */)
{
}
ODBCAppender::SQLHDBC ODBCAppender::getConnection(log4cxx::helpers::Pool& p)
{
#if LOG4CXX_HAVE_ODBC
SQLRETURN ret;
if (env == SQL_NULL_HENV)
{
ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
if (ret < 0)
{
SQLException ex(SQL_HANDLE_ENV, env, "Failed to allocate SQL handle.", p);
env = SQL_NULL_HENV;
throw ex;
}
ret = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER);
if (ret < 0)
{
SQLException ex(SQL_HANDLE_ENV, env, "Failed to set odbc version.", p);
SQLFreeHandle(SQL_HANDLE_ENV, env);
env = SQL_NULL_HENV;
throw ex;
}
}
if (connection == SQL_NULL_HDBC)
{
ret = SQLAllocHandle(SQL_HANDLE_DBC, env, &connection);
if (ret < 0)
{
SQLException ex(SQL_HANDLE_DBC, connection, "Failed to allocate sql handle.", p);
connection = SQL_NULL_HDBC;
throw ex;
}
SQLWCHAR* wURL = Transcoder::wencode(databaseURL, p);
wchar_t szOutConnectionString[1024];
SQLSMALLINT nOutConnctionLength = 0;
ret = SQLDriverConnectW( connection, NULL,
wURL, SQL_NTS,
szOutConnectionString, sizeof( szOutConnectionString ),
&nOutConnctionLength, SQL_DRIVER_NOPROMPT );
if (ret < 0)
{
SQLException ex(SQL_HANDLE_DBC, connection, "Failed to connect to database.", p);
SQLFreeHandle(SQL_HANDLE_DBC, connection);
connection = SQL_NULL_HDBC;
throw ex;
}
}
return connection;
#else
return 0;
#endif
}
void ODBCAppender::close()
{
if (closed) {
return;
}
Pool p;
try
{
flushBuffer(p);
}
catch (SQLException& e)
{
errorHandler->error(LOG4CXX_STR("Error closing connection"),
e, ErrorCode::GENERIC_FAILURE);
}
#if LOG4CXX_HAVE_ODBC
if (connection != SQL_NULL_HDBC)
{
SQLDisconnect(connection);
SQLFreeHandle(SQL_HANDLE_DBC, connection);
}
if (env != SQL_NULL_HENV)
{
SQLFreeHandle(SQL_HANDLE_ENV, env);
}
#endif
this->closed = true;
}
void ODBCAppender::flushBuffer(Pool& p)
{
std::list<spi::LoggingEventPtr>::iterator i;
for (i = buffer.begin(); i != buffer.end(); i++)
{
try
{
const LoggingEventPtr& logEvent = *i;
LogString sql = getLogStatement(logEvent, p);
execute(sql, p);
}
catch (SQLException& e)
{
errorHandler->error(LOG4CXX_STR("Failed to excute sql"), e,
ErrorCode::FLUSH_FAILURE);
}
}
// clear the buffer of reported events
buffer.clear();
}
void ODBCAppender::setSql(const LogString& s)
{
sqlStatement = s;
if (getLayout() == 0)
{
this->setLayout(new PatternLayout(s));
}
else
{
PatternLayoutPtr patternLayout = this->getLayout();
if (patternLayout != 0)
{
patternLayout->setConversionPattern(s);
}
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/xml/domconfigurator.h>
#include <log4cxx/appender.h>
#include <log4cxx/layout.h>
#include <log4cxx/logger.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/level.h>
#include <log4cxx/spi/filter.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/loader.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/config/propertysetter.h>
#include <log4cxx/spi/errorhandler.h>
#include <log4cxx/spi/loggerfactory.h>
#include <log4cxx/defaultloggerfactory.h>
#include <log4cxx/helpers/filewatchdog.h>
#include <log4cxx/helpers/synchronized.h>
#include <log4cxx/spi/loggerrepository.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/helpers/pool.h>
#include <sstream>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/rolling/rollingfileappender.h>
#include <log4cxx/rolling/filterbasedtriggeringpolicy.h>
#include <apr_xml.h>
#include <log4cxx/helpers/bytebuffer.h>
#include <log4cxx/helpers/charsetdecoder.h>
#include <log4cxx/net/smtpappender.h>
using namespace log4cxx;
using namespace log4cxx::xml;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
using namespace log4cxx::config;
using namespace log4cxx::rolling;
#if APR_HAS_THREADS
class XMLWatchdog : public FileWatchdog
{
public:
XMLWatchdog(const File& filename) : FileWatchdog(filename)
{
}
/**
Call DOMConfigurator#doConfigure with the
<code>filename</code> to reconfigure log4cxx.
*/
void doOnChange()
{
DOMConfigurator().doConfigure(file,
LogManager::getLoggerRepository());
}
};
#endif
IMPLEMENT_LOG4CXX_OBJECT(DOMConfigurator)
#define CONFIGURATION_TAG "log4j:configuration"
#define OLD_CONFIGURATION_TAG "configuration"
#define APPENDER_TAG "appender"
#define APPENDER_REF_TAG "appender-ref"
#define PARAM_TAG "param"
#define LAYOUT_TAG "layout"
#define ROLLING_POLICY_TAG "rollingPolicy"
#define TRIGGERING_POLICY_TAG "triggeringPolicy"
#define CATEGORY "category"
#define LOGGER "logger"
#define LOGGER_REF "logger-ref"
#define CATEGORY_FACTORY_TAG "categoryFactory"
#define NAME_ATTR "name"
#define CLASS_ATTR "class"
#define VALUE_ATTR "value"
#define ROOT_TAG "root"
#define ROOT_REF "root-ref"
#define LEVEL_TAG "level"
#define PRIORITY_TAG "priority"
#define FILTER_TAG "filter"
#define ERROR_HANDLER_TAG "errorHandler"
#define REF_ATTR "ref"
#define ADDITIVITY_ATTR "additivity"
#define THRESHOLD_ATTR "threshold"
#define CONFIG_DEBUG_ATTR "configDebug"
#define INTERNAL_DEBUG_ATTR "debug"
DOMConfigurator::DOMConfigurator()
: props(), repository() {
}
void DOMConfigurator::addRef() const {
ObjectImpl::addRef();
}
void DOMConfigurator::releaseRef() const {
ObjectImpl::releaseRef();
}
/**
Used internally to parse appenders by IDREF name.
*/
AppenderPtr DOMConfigurator::findAppenderByName(log4cxx::helpers::Pool& p,
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* element,
apr_xml_doc* doc,
const LogString& appenderName,
AppenderMap& appenders) {
AppenderPtr appender;
std::string tagName(element->name);
if (tagName == APPENDER_TAG) {
if (appenderName == getAttribute(utf8Decoder, element, NAME_ATTR)) {
appender = parseAppender(p, utf8Decoder, element, doc, appenders);
}
}
if (element->first_child && !appender) {
appender = findAppenderByName(p, utf8Decoder, element->first_child, doc, appenderName, appenders);
}
if (element->next && !appender) {
appender = findAppenderByName(p, utf8Decoder, element->next, doc, appenderName, appenders);
}
return appender;
}
/**
Used internally to parse appenders by IDREF element.
*/
AppenderPtr DOMConfigurator::findAppenderByReference(
log4cxx::helpers::Pool& p,
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* appenderRef,
apr_xml_doc* doc,
AppenderMap& appenders)
{
LogString appenderName(subst(getAttribute(utf8Decoder, appenderRef, REF_ATTR)));
AppenderMap::const_iterator match = appenders.find(appenderName);
AppenderPtr appender;
if (match != appenders.end()) {
appender = match->second;
} else if (doc) {
appender = findAppenderByName(p, utf8Decoder, doc->root, doc, appenderName, appenders);
if (appender) {
appenders.insert(AppenderMap::value_type(appenderName, appender));
}
}
if (!appender) {
LogLog::error(LOG4CXX_STR("No appender named [")+
appenderName+LOG4CXX_STR("] could be found."));
}
return appender;
}
/**
Used internally to parse an appender element.
*/
AppenderPtr DOMConfigurator::parseAppender(Pool& p,
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* appenderElement,
apr_xml_doc* doc,
AppenderMap& appenders)
{
LogString className(subst(getAttribute(utf8Decoder, appenderElement, CLASS_ATTR)));
LogLog::debug(LOG4CXX_STR("Class name: [") + className+LOG4CXX_STR("]"));
try
{
ObjectPtr instance = Loader::loadClass(className).newInstance();
AppenderPtr appender = instance;
PropertySetter propSetter(appender);
appender->setName(subst(getAttribute(utf8Decoder, appenderElement, NAME_ATTR)));
for(apr_xml_elem* currentElement = appenderElement->first_child;
currentElement;
currentElement = currentElement->next) {
std::string tagName(currentElement->name);
// Parse appender parameters
if (tagName == PARAM_TAG)
{
setParameter(p, utf8Decoder, currentElement, propSetter);
}
// Set appender layout
else if (tagName == LAYOUT_TAG)
{
appender->setLayout(parseLayout(p, utf8Decoder, currentElement));
}
// Add filters
else if (tagName == FILTER_TAG)
{
std::vector<log4cxx::spi::FilterPtr> filters;
parseFilters(p, utf8Decoder, currentElement, filters);
for(std::vector<log4cxx::spi::FilterPtr>::iterator iter = filters.begin();
iter != filters.end();
iter++) {
appender->addFilter(*iter);
}
}
else if (tagName == ERROR_HANDLER_TAG)
{
parseErrorHandler(p, utf8Decoder, currentElement, appender, doc, appenders);
}
else if (tagName == ROLLING_POLICY_TAG)
{
RollingPolicyPtr rollPolicy(parseRollingPolicy(p, utf8Decoder, currentElement));
RollingFileAppenderPtr rfa(appender);
if (rfa != NULL) {
rfa->setRollingPolicy(rollPolicy);
}
}
else if (tagName == TRIGGERING_POLICY_TAG)
{
ObjectPtr policy(parseTriggeringPolicy(p, utf8Decoder, currentElement));
RollingFileAppenderPtr rfa(appender);
if (rfa != NULL) {
rfa->setTriggeringPolicy(policy);
} else {
log4cxx::net::SMTPAppenderPtr smtpa(appender);
if (smtpa != NULL) {
log4cxx::spi::TriggeringEventEvaluatorPtr evaluator(policy);
smtpa->setEvaluator(evaluator);
}
}
}
else if (tagName == APPENDER_REF_TAG)
{
LogString refName = subst(getAttribute(utf8Decoder, currentElement, REF_ATTR));
if(appender->instanceof(AppenderAttachable::getStaticClass()))
{
AppenderAttachablePtr aa(appender);
LogLog::debug(LOG4CXX_STR("Attaching appender named [")+
refName+LOG4CXX_STR("] to appender named [")+
appender->getName()+LOG4CXX_STR("]."));
aa->addAppender(findAppenderByReference(p, utf8Decoder, currentElement, doc, appenders));
}
else
{
LogLog::error(LOG4CXX_STR("Requesting attachment of appender named [")+
refName+ LOG4CXX_STR("] to appender named [")+ appender->getName()+
LOG4CXX_STR("] which does not implement AppenderAttachable."));
}
}
}
propSetter.activate(p);
return appender;
}
/* Yes, it's ugly. But all of these exceptions point to the same
problem: we can't create an Appender */
catch (Exception& oops)
{
LogLog::error(LOG4CXX_STR("Could not create an Appender. Reported error follows."),
oops);
return 0;
}
}
/**
Used internally to parse an {@link ErrorHandler} element.
*/
void DOMConfigurator::parseErrorHandler(Pool& p,
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* element,
AppenderPtr& appender,
apr_xml_doc* doc,
AppenderMap& appenders)
{
ErrorHandlerPtr eh = OptionConverter::instantiateByClassName(
subst(getAttribute(utf8Decoder, element, CLASS_ATTR)),
ErrorHandler::getStaticClass(),
0);
if(eh != 0)
{
eh->setAppender(appender);
PropertySetter propSetter(eh);
for (apr_xml_elem* currentElement = element->first_child;
currentElement;
currentElement = currentElement->next) {
std::string tagName(currentElement->name);
if(tagName == PARAM_TAG)
{
setParameter(p, utf8Decoder, currentElement, propSetter);
}
else if(tagName == APPENDER_REF_TAG)
{
eh->setBackupAppender(findAppenderByReference(p, utf8Decoder, currentElement, doc, appenders));
}
else if(tagName == LOGGER_REF)
{
LogString loggerName(getAttribute(utf8Decoder, currentElement, REF_ATTR));
LoggerPtr logger = repository->getLogger(loggerName, loggerFactory);
eh->setLogger(logger);
}
else if(tagName == ROOT_REF)
{
LoggerPtr root = repository->getRootLogger();
eh->setLogger(root);
}
}
propSetter.activate(p);
// appender->setErrorHandler(eh);
}
}
/**
Used internally to parse a filter element.
*/
void DOMConfigurator::parseFilters(Pool& p,
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* element,
std::vector<log4cxx::spi::FilterPtr>& filters)
{
LogString clazz = subst(getAttribute(utf8Decoder, element, CLASS_ATTR));
FilterPtr filter = OptionConverter::instantiateByClassName(clazz,
Filter::getStaticClass(), 0);
if(filter != 0)
{
PropertySetter propSetter(filter);
for (apr_xml_elem* currentElement = element->first_child;
currentElement;
currentElement = currentElement->next)
{
std::string tagName(currentElement->name);
if(tagName == PARAM_TAG)
{
setParameter(p, utf8Decoder, currentElement, propSetter);
}
}
propSetter.activate(p);
filters.push_back(filter);
}
}
/**
Used internally to parse an category or logger element.
*/
void DOMConfigurator::parseLogger(
log4cxx::helpers::Pool& p,
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* loggerElement,
apr_xml_doc* doc,
AppenderMap& appenders)
{
// Create a new Logger object from the <category> element.
LogString loggerName = subst(getAttribute(utf8Decoder, loggerElement, NAME_ATTR));
LogLog::debug(LOG4CXX_STR("Retreiving an instance of Logger."));
LoggerPtr logger = repository->getLogger(loggerName, loggerFactory);
// Setting up a logger needs to be an atomic operation, in order
// to protect potential log operations while logger
// configuration is in progress.
synchronized sync(logger->getMutex());
bool additivity = OptionConverter::toBoolean(
subst(getAttribute(utf8Decoder, loggerElement, ADDITIVITY_ATTR)),
true);
LogLog::debug(LOG4CXX_STR("Setting [")+logger->getName()+LOG4CXX_STR("] additivity to [")+
(additivity ? LogString(LOG4CXX_STR("true")) : LogString(LOG4CXX_STR("false")))+LOG4CXX_STR("]."));
logger->setAdditivity(additivity);
parseChildrenOfLoggerElement(p, utf8Decoder, loggerElement, logger, false, doc, appenders);
}
/**
Used internally to parse the logger factory element.
*/
void DOMConfigurator::parseLoggerFactory(
log4cxx::helpers::Pool& p,
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* factoryElement)
{
LogString className(subst(getAttribute(utf8Decoder, factoryElement, CLASS_ATTR)));
if(className.empty())
{
LogLog::error(LOG4CXX_STR("Logger Factory tag class attribute not found."));
LogLog::debug(LOG4CXX_STR("No Logger Factory configured."));
}
else
{
LogLog::debug(LOG4CXX_STR("Desired logger factory: [")+className+LOG4CXX_STR("]"));
loggerFactory = OptionConverter::instantiateByClassName(
className,
LoggerFactory::getStaticClass(),
0);
PropertySetter propSetter(loggerFactory);
for (apr_xml_elem* currentElement = factoryElement->first_child;
currentElement;
currentElement = currentElement->next) {
std::string tagName(currentElement->name);
if (tagName == PARAM_TAG) {
setParameter(p, utf8Decoder, currentElement, propSetter);
}
}
}
}
/**
Used internally to parse the root logger element.
*/
void DOMConfigurator::parseRoot(
log4cxx::helpers::Pool& p,
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* rootElement,
apr_xml_doc* doc,
AppenderMap& appenders)
{
LoggerPtr root = repository->getRootLogger();
// logger configuration needs to be atomic
synchronized sync(root->getMutex());
parseChildrenOfLoggerElement(p, utf8Decoder, rootElement, root, true, doc, appenders);
}
/**
Used internally to parse the children of a logger element.
*/
void DOMConfigurator::parseChildrenOfLoggerElement(
log4cxx::helpers::Pool& p,
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* loggerElement, LoggerPtr logger, bool isRoot,
apr_xml_doc* doc,
AppenderMap& appenders)
{
PropertySetter propSetter(logger);
// Remove all existing appenders from logger. They will be
// reconstructed if need be.
logger->removeAllAppenders();
for (apr_xml_elem* currentElement = loggerElement->first_child;
currentElement;
currentElement = currentElement->next) {
std::string tagName(currentElement->name);
if (tagName == APPENDER_REF_TAG)
{
AppenderPtr appender = findAppenderByReference(p, utf8Decoder, currentElement, doc, appenders);
LogString refName = subst(getAttribute(utf8Decoder, currentElement, REF_ATTR));
if(appender != 0)
{
LogLog::debug(LOG4CXX_STR("Adding appender named [")+ refName+
LOG4CXX_STR("] to logger [")+logger->getName()+LOG4CXX_STR("]."));
}
else
{
LogLog::debug(LOG4CXX_STR("Appender named [")+ refName +
LOG4CXX_STR("] not found."));
}
logger->addAppender(appender);
}
else if(tagName == LEVEL_TAG)
{
parseLevel(p, utf8Decoder, currentElement, logger, isRoot);
}
else if(tagName == PRIORITY_TAG)
{
parseLevel(p, utf8Decoder, currentElement, logger, isRoot);
}
else if(tagName == PARAM_TAG)
{
setParameter(p, utf8Decoder, currentElement, propSetter);
}
}
propSetter.activate(p);
}
/**
Used internally to parse a layout element.
*/
LayoutPtr DOMConfigurator::parseLayout (
log4cxx::helpers::Pool& p,
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* layout_element)
{
LogString className(subst(getAttribute(utf8Decoder, layout_element, CLASS_ATTR)));
LogLog::debug(LOG4CXX_STR("Parsing layout of class: \"")+className+LOG4CXX_STR("\""));
try
{
ObjectPtr instance = Loader::loadClass(className).newInstance();
LayoutPtr layout = instance;
PropertySetter propSetter(layout);
for(apr_xml_elem* currentElement = layout_element->first_child;
currentElement;
currentElement = currentElement->next) {
std::string tagName(currentElement->name);
if(tagName == PARAM_TAG)
{
setParameter(p, utf8Decoder, currentElement, propSetter);
}
}
propSetter.activate(p);
return layout;
}
catch (Exception& oops)
{
LogLog::error(LOG4CXX_STR("Could not create the Layout. Reported error follows."),
oops);
return 0;
}
}
/**
Used internally to parse a triggering policy
*/
ObjectPtr DOMConfigurator::parseTriggeringPolicy (
log4cxx::helpers::Pool& p,
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* layout_element)
{
LogString className = subst(getAttribute(utf8Decoder, layout_element, CLASS_ATTR));
LogLog::debug(LOG4CXX_STR("Parsing triggering policy of class: \"")+className+LOG4CXX_STR("\""));
try
{
ObjectPtr instance = Loader::loadClass(className).newInstance();
PropertySetter propSetter(instance);
for (apr_xml_elem* currentElement = layout_element->first_child;
currentElement;
currentElement = currentElement->next) {
std::string tagName(currentElement->name);
if(tagName == PARAM_TAG)
{
setParameter(p, utf8Decoder, currentElement, propSetter);
}
else if (tagName == FILTER_TAG) {
std::vector<log4cxx::spi::FilterPtr> filters;
parseFilters(p, utf8Decoder, currentElement, filters);
FilterBasedTriggeringPolicyPtr fbtp(instance);
if (fbtp != NULL) {
for(std::vector<log4cxx::spi::FilterPtr>::iterator iter = filters.begin();
iter != filters.end();
iter++) {
fbtp->addFilter(*iter);
}
}
}
}
propSetter.activate(p);
return instance;
}
catch (Exception& oops)
{
LogLog::error(LOG4CXX_STR("Could not create the TriggeringPolicy. Reported error follows."),
oops);
return 0;
}
}
/**
Used internally to parse a triggering policy
*/
RollingPolicyPtr DOMConfigurator::parseRollingPolicy (
log4cxx::helpers::Pool& p,
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* layout_element)
{
LogString className = subst(getAttribute(utf8Decoder, layout_element, CLASS_ATTR));
LogLog::debug(LOG4CXX_STR("Parsing rolling policy of class: \"")+className+LOG4CXX_STR("\""));
try
{
ObjectPtr instance = Loader::loadClass(className).newInstance();
RollingPolicyPtr layout = instance;
PropertySetter propSetter(layout);
for(apr_xml_elem* currentElement = layout_element->first_child;
currentElement;
currentElement = currentElement->next) {
std::string tagName(currentElement->name);
if(tagName == PARAM_TAG)
{
setParameter(p, utf8Decoder, currentElement, propSetter);
}
}
propSetter.activate(p);
return layout;
}
catch (Exception& oops)
{
LogLog::error(LOG4CXX_STR("Could not create the RollingPolicy. Reported error follows."),
oops);
return 0;
}
}
/**
Used internally to parse a level element.
*/
void DOMConfigurator::parseLevel(
log4cxx::helpers::Pool& p,
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* element, LoggerPtr logger, bool isRoot)
{
LogString loggerName = logger->getName();
if(isRoot)
{
loggerName = LOG4CXX_STR("root");
}
LogString levelStr(subst(getAttribute(utf8Decoder, element, VALUE_ATTR)));
LogLog::debug(LOG4CXX_STR("Level value for ")+loggerName+LOG4CXX_STR(" is [")+levelStr+LOG4CXX_STR("]."));
if (StringHelper::equalsIgnoreCase(levelStr,LOG4CXX_STR("INHERITED"), LOG4CXX_STR("inherited"))
|| StringHelper::equalsIgnoreCase(levelStr, LOG4CXX_STR("NULL"), LOG4CXX_STR("null")))
{
if(isRoot)
{
LogLog::error(LOG4CXX_STR("Root level cannot be inherited. Ignoring directive."));
}
else
{
logger->setLevel(0);
}
}
else
{
LogString className(subst(getAttribute(utf8Decoder, element, CLASS_ATTR)));
if (className.empty())
{
logger->setLevel(OptionConverter::toLevel(levelStr, Level::getDebug()));
}
else
{
LogLog::debug(LOG4CXX_STR("Desired Level sub-class: [") + className + LOG4CXX_STR("]"));
try
{
Level::LevelClass& levelClass =
(Level::LevelClass&)Loader::loadClass(className);
LevelPtr level = levelClass.toLevel(levelStr);
logger->setLevel(level);
}
catch (Exception& oops)
{
LogLog::error(
LOG4CXX_STR("Could not create level [") + levelStr +
LOG4CXX_STR("]. Reported error follows."),
oops);
return;
}
catch (...)
{
LogLog::error(
LOG4CXX_STR("Could not create level [") + levelStr);
return;
}
}
}
LogLog::debug(loggerName + LOG4CXX_STR(" level set to ") +
logger->getEffectiveLevel()->toString());
}
void DOMConfigurator::setParameter(log4cxx::helpers::Pool& p,
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* elem,
PropertySetter& propSetter)
{
LogString name(subst(getAttribute(utf8Decoder, elem, NAME_ATTR)));
LogString value(subst(getAttribute(utf8Decoder, elem, VALUE_ATTR)));
value = subst(value);
propSetter.setProperty(name, value, p);
}
void DOMConfigurator::doConfigure(const File& filename, spi::LoggerRepositoryPtr& repository1)
{
repository1->setConfigured(true);
this->repository = repository1;
LogString msg(LOG4CXX_STR("DOMConfigurator configuring file "));
msg.append(filename.getPath());
msg.append(LOG4CXX_STR("..."));
LogLog::debug(msg);
loggerFactory = new DefaultLoggerFactory();
Pool p;
apr_file_t *fd;
log4cxx_status_t rv = filename.open(&fd, APR_READ, APR_OS_DEFAULT, p);
if (rv != APR_SUCCESS) {
LogString msg2(LOG4CXX_STR("Could not open file ["));
msg2.append(filename.getPath());
msg2.append(LOG4CXX_STR("]."));
LogLog::error(msg2);
} else {
apr_xml_parser *parser;
apr_xml_doc *doc;
rv = apr_xml_parse_file(p.getAPRPool(), &parser, &doc, fd, 2000);
if (rv != APR_SUCCESS) {
char errbuf[2000];
char errbufXML[2000];
LogString msg2(LOG4CXX_STR("Error parsing file ["));
msg2.append(filename.getPath());
msg2.append(LOG4CXX_STR("], "));
apr_strerror(rv, errbuf, sizeof(errbuf));
LOG4CXX_DECODE_CHAR(lerrbuf, std::string(errbuf));
apr_xml_parser_geterror(parser, errbufXML, sizeof(errbufXML));
LOG4CXX_DECODE_CHAR(lerrbufXML, std::string(errbufXML));
msg2.append(lerrbuf);
msg2.append(lerrbufXML);
LogLog::error(msg2);
} else {
AppenderMap appenders;
CharsetDecoderPtr utf8Decoder(CharsetDecoder::getUTF8Decoder());
parse(p, utf8Decoder, doc->root, doc, appenders);
}
}
}
void DOMConfigurator::configure(const std::string& filename)
{
File file(filename);
DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository());
}
#if LOG4CXX_WCHAR_T_API
void DOMConfigurator::configure(const std::wstring& filename)
{
File file(filename);
DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository());
}
#endif
#if LOG4CXX_UNICHAR_API
void DOMConfigurator::configure(const std::basic_string<UniChar>& filename)
{
File file(filename);
DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository());
}
#endif
#if LOG4CXX_CFSTRING_API
void DOMConfigurator::configure(const CFStringRef& filename)
{
File file(filename);
DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository());
}
#endif
void DOMConfigurator::configureAndWatch(const std::string& filename)
{
configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY);
}
#if LOG4CXX_WCHAR_T_API
void DOMConfigurator::configureAndWatch(const std::wstring& filename)
{
configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY);
}
#endif
#if LOG4CXX_UNICHAR_API
void DOMConfigurator::configureAndWatch(const std::basic_string<UniChar>& filename)
{
configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY);
}
#endif
#if LOG4CXX_CFSTRING_API
void DOMConfigurator::configureAndWatch(const CFStringRef& filename)
{
configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY);
}
#endif
void DOMConfigurator::configureAndWatch(const std::string& filename, long delay)
{
File file(filename);
#if APR_HAS_THREADS
XMLWatchdog * xdog = new XMLWatchdog(file);
xdog->setDelay(delay);
xdog->start();
#else
DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository());
#endif
}
#if LOG4CXX_WCHAR_T_API
void DOMConfigurator::configureAndWatch(const std::wstring& filename, long delay)
{
File file(filename);
#if APR_HAS_THREADS
XMLWatchdog * xdog = new XMLWatchdog(file);
xdog->setDelay(delay);
xdog->start();
#else
DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository());
#endif
}
#endif
#if LOG4CXX_UNICHAR_API
void DOMConfigurator::configureAndWatch(const std::basic_string<UniChar>& filename, long delay)
{
File file(filename);
#if APR_HAS_THREADS
XMLWatchdog * xdog = new XMLWatchdog(file);
xdog->setDelay(delay);
xdog->start();
#else
DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository());
#endif
}
#endif
#if LOG4CXX_CFSTRING_API
void DOMConfigurator::configureAndWatch(const CFStringRef& filename, long delay)
{
File file(filename);
#if APR_HAS_THREADS
XMLWatchdog * xdog = new XMLWatchdog(file);
xdog->setDelay(delay);
xdog->start();
#else
DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository());
#endif
}
#endif
void DOMConfigurator::parse(
Pool& p,
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* element,
apr_xml_doc* doc,
AppenderMap& appenders)
{
std::string rootElementName(element->name);
if (rootElementName != CONFIGURATION_TAG)
{
if(rootElementName == OLD_CONFIGURATION_TAG)
{
//LogLog::warn(LOG4CXX_STR("The <")+String(OLD_CONFIGURATION_TAG)+
// LOG4CXX_STR("> element has been deprecated."));
//LogLog::warn(LOG4CXX_STR("Use the <")+String(CONFIGURATION_TAG)+
// LOG4CXX_STR("> element instead."));
}
else
{
LogLog::error(LOG4CXX_STR("DOM element is - not a <configuration> element."));
return;
}
}
LogString debugAttrib = subst(getAttribute(utf8Decoder, element, INTERNAL_DEBUG_ATTR));
static const LogString NuLL(LOG4CXX_STR("NULL"));
LogLog::debug(LOG4CXX_STR("debug attribute= \"") + debugAttrib +LOG4CXX_STR("\"."));
// if the log4j.dtd is not specified in the XML file, then the
// "debug" attribute is returned as the empty string.
if(!debugAttrib.empty() && debugAttrib != NuLL)
{
LogLog::setInternalDebugging(OptionConverter::toBoolean(debugAttrib, true));
}
else
{
LogLog::debug(LOG4CXX_STR("Ignoring internalDebug attribute."));
}
LogString confDebug = subst(getAttribute(utf8Decoder, element, CONFIG_DEBUG_ATTR));
if(!confDebug.empty() && confDebug != NuLL)
{
LogLog::warn(LOG4CXX_STR("The \"configDebug\" attribute is deprecated."));
LogLog::warn(LOG4CXX_STR("Use the \"internalDebug\" attribute instead."));
LogLog::setInternalDebugging(OptionConverter::toBoolean(confDebug, true));
}
LogString thresholdStr = subst(getAttribute(utf8Decoder, element, THRESHOLD_ATTR));
LogLog::debug(LOG4CXX_STR("Threshold =\"") + thresholdStr +LOG4CXX_STR("\"."));
if(!thresholdStr.empty() && thresholdStr != NuLL)
{
repository->setThreshold(thresholdStr);
}
apr_xml_elem* currentElement;
for(currentElement = element->first_child;
currentElement;
currentElement = currentElement->next) {
std::string tagName(currentElement->name);
if (tagName == CATEGORY_FACTORY_TAG)
{
parseLoggerFactory(p, utf8Decoder, currentElement);
}
}
for(currentElement = element->first_child;
currentElement;
currentElement = currentElement->next) {
std::string tagName(currentElement->name);
if (tagName == CATEGORY || tagName == LOGGER)
{
parseLogger(p, utf8Decoder, currentElement, doc, appenders);
}
else if (tagName == ROOT_TAG)
{
parseRoot(p, utf8Decoder, currentElement, doc, appenders);
}
}
}
LogString DOMConfigurator::subst(const LogString& value)
{
try
{
return OptionConverter::substVars(value, props);
}
catch(IllegalArgumentException& e)
{
LogLog::warn(LOG4CXX_STR("Could not perform variable substitution."), e);
return value;
}
}
LogString DOMConfigurator::getAttribute(
log4cxx::helpers::CharsetDecoderPtr& utf8Decoder,
apr_xml_elem* element,
const std::string& attrName) {
LogString attrValue;
for(apr_xml_attr* attr = element->attr;
attr;
attr = attr->next) {
if (attrName == attr->name) {
ByteBuffer buf((char*) attr->value, strlen(attr->value));
utf8Decoder->decode(buf, attrValue);
}
}
return attrValue;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_WIN32)
#include <log4cxx/nt/outputdebugstringappender.h>
#include <log4cxx/helpers/transcoder.h>
#include "windows.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::nt;
IMPLEMENT_LOG4CXX_OBJECT(OutputDebugStringAppender)
OutputDebugStringAppender::OutputDebugStringAppender() {
}
void OutputDebugStringAppender::append(const spi::LoggingEventPtr& event, Pool& p)
{
LogString buf;
layout->format(buf, event, p);
#if LOG4CXX_WCHAR_T_API
LOG4CXX_ENCODE_WCHAR(wstr, buf);
::OutputDebugStringW(wstr.c_str());
#else
LOG4CXX_ENCODE_CHAR(str, buf);
::OutputDebugStringA(str.c_str());
#endif
}
#endif
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/properties.h>
#include <log4cxx/helpers/inputstreamreader.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/helpers/pool.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
class PropertyParser
{
public:
void parse(LogString& in, Properties& properties)
{
LogString key, element;
LexemType lexemType = BEGIN;
logchar c;
bool finished = false;
if (!get(in, c))
{
return;
}
while (!finished)
{
switch(lexemType)
{
case BEGIN:
switch(c)
{
case 0x20: // ' '
case 0x08: // '\t'
case 0x0A: // '\n'
case 0x0D: // '\r'
if (!get(in, c))
finished = true;
break;
case 0x23: // '#'
case 0x21: // '!'
lexemType = COMMENT;
if (!get(in, c))
finished = true;
break;
default:
lexemType = KEY;
break;
}
break;
case KEY:
switch(c)
{
case 0x5C: // '\\'
lexemType = KEY_ESCAPE;
if (!get(in, c))
finished = true;
break;
case 0x08: // '\t'
case 0x20: // ' '
case 0x3A: // ':'
case 0x3D: // '='
lexemType = DELIMITER;
if (!get(in, c))
finished = true;
break;
case 0x0A:
case 0x0D:
// key associated with an empty string element
properties.setProperty(key, LogString());
key.erase(key.begin(), key.end());
lexemType = BEGIN;
if (!get(in, c))
finished = true;
break;
default:
key.append(1, c);
if (!get(in, c))
finished = true;
break;
}
break;
case KEY_ESCAPE:
switch(c)
{
case 0x08: // '\t'
case 0x20: // ' '
case 0x3A: // ':'
case 0x3D: // '='
case 0x5C: // '\\'
key.append(1, c);
lexemType = KEY;
if (!get(in, c))
finished = true;
break;
case 0x0A: // '\n'
lexemType = KEY_CONTINUE;
if (!get(in, c))
finished = true;
break;
case 0x0D: // '\r'
lexemType = KEY_CONTINUE2;
if (!get(in, c))
finished = true;
break;
}
break;
case KEY_CONTINUE:
switch(c)
{
case 0x20: // ' '
case 0x08: // '\t'
if (!get(in, c))
finished = true;
break;
default:
lexemType = KEY;
break;
}
break;
case KEY_CONTINUE2:
switch(c)
{
case 0x0A: // '\n'
if (!get(in, c))
finished = true;
lexemType = KEY_CONTINUE;
break;
default:
lexemType = KEY_CONTINUE;
break;
}
break;
case DELIMITER:
switch(c)
{
case 0x08: // '\t'
case 0x20: // ' '
case 0x3A: // ':'
case 0x3D: // '='
if (!get(in, c))
finished = true;
break;
default:
lexemType = ELEMENT;
break;
}
break;
case ELEMENT:
switch(c)
{
case 0x5C: // '\\'
lexemType = ELEMENT_ESCAPE;
if (!get(in, c))
finished = true;
break;
case 0x0A: // '\n'
case 0x0D: // '\r'
// key associated with an empty string element
properties.setProperty(key, element);
key.erase(key.begin(), key.end());
element.erase(element.begin(), element.end());
lexemType = BEGIN;
if (!get(in, c))
finished = true;
break;
default:
element.append(1, c);
if (!get(in, c))
finished = true;
break;
}
break;
case ELEMENT_ESCAPE:
switch(c)
{
case 0x08: // '\t'
case 0x20: // ' '
case 0x6E: // 'n'
case 0x72: // 'r'
case 0x27: // '\''
case 0x5C: // '\\'
case 0x22: // '\"'
case 0x3A: // ':'
default:
element.append(1, c);
lexemType = ELEMENT;
if (!get(in, c))
finished = true;
break;
case 0x0A: // '\n'
lexemType = ELEMENT_CONTINUE;
if (!get(in, c))
finished = true;
break;
case 0x0D: // '\r'
lexemType = ELEMENT_CONTINUE2;
if (!get(in, c))
finished = true;
break;
}
break;
case ELEMENT_CONTINUE:
switch(c)
{
case 0x20: // ' '
case 0x08: // '\t'
if (!get(in, c))
finished = true;
break;
default:
lexemType = ELEMENT;
break;
}
break;
case ELEMENT_CONTINUE2:
switch(c)
{
case 0x20: // '\n'
if (!get(in, c))
finished = true;
lexemType = ELEMENT_CONTINUE;
break;
default:
lexemType = ELEMENT_CONTINUE;
break;
}
break;
case COMMENT:
if (c == 0x0A || c == 0x0D)
{
lexemType = BEGIN;
}
if (!get(in, c))
finished = true;
break;
}
}
if (!key.empty())
{
properties.setProperty(key, element);
}
}
protected:
bool get(LogString& in, logchar& c)
{
if (in.empty()) {
c = 0;
return false;
}
c = in[0];
in.erase(in.begin());
return true;
}
typedef enum
{
BEGIN,
KEY,
KEY_ESCAPE,
KEY_CONTINUE,
KEY_CONTINUE2,
DELIMITER,
ELEMENT,
ELEMENT_ESCAPE,
ELEMENT_CONTINUE,
ELEMENT_CONTINUE2,
COMMENT
}
LexemType;
};
Properties::Properties() : properties(new PropertyMap()) {
}
Properties::~Properties() {
delete properties;
}
LogString Properties::setProperty(const LogString& key, const LogString& value) {
return put(key, value);
}
LogString Properties::put(const LogString& key, const LogString& value)
{
LogString oldValue((*properties)[key]);
(*properties)[key] = value;
//tcout << ASCII_STR("setting property key=") << key << ASCII_STR(", value=") << value << std::endl;
return oldValue;
}
LogString Properties::getProperty(const LogString& key) const {
return get(key);
}
LogString Properties::get(const LogString& key) const
{
PropertyMap::const_iterator it = properties->find(key);
return (it != properties->end()) ? it->second : LogString();
}
void Properties::load(InputStreamPtr inStream) {
Pool pool;
InputStreamReaderPtr lineReader(
new InputStreamReader(inStream, CharsetDecoder::getISOLatinDecoder()));
LogString contents = lineReader->read(pool);
properties->clear();
PropertyParser parser;
parser.parse(contents, *this);
}
std::vector<LogString> Properties::propertyNames() const
{
std::vector<LogString> names;
names.reserve(properties->size());
PropertyMap::const_iterator it;
for (it = properties->begin(); it != properties->end(); it++)
{
const LogString& key = it->first;
names.push_back(key);
}
return names;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/helpers/locale.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
Locale::Locale(const LogString& language1)
: language(language1)
{
}
Locale::Locale(const LogString& language1, const LogString& country1)
: language(language1), country(country1)
{
}
Locale::Locale(const LogString& language1, const LogString& country1,
const LogString& variant1)
: language(language1), country(country1), variant(variant1)
{
}
const LogString& Locale::getLanguage() const
{
return language;
}
const LogString& Locale::getCountry() const
{
return country;
}
const LogString& Locale::getVariant() const
{
return variant;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if (defined(WIN32) || defined(_WIN32)) && !defined(_WIN32_WCE)
#include <windows.h>
#undef ERROR
#include <log4cxx/nt/nteventlogappender.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/level.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/helpers/pool.h>
#include <apr_strings.h>
using namespace log4cxx;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
using namespace log4cxx::nt;
class CCtUserSIDHelper
{
public:
static bool FreeSid(SID * pSid)
{
return ::HeapFree(GetProcessHeap(), 0, (LPVOID)pSid) != 0;
}
static bool CopySid(SID * * ppDstSid, SID * pSrcSid)
{
bool bSuccess = false;
DWORD dwLength = ::GetLengthSid(pSrcSid);
*ppDstSid = (SID *) ::HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY, dwLength);
if (::CopySid(dwLength, *ppDstSid, pSrcSid))
{
bSuccess = true;
}
else
{
FreeSid(*ppDstSid);
}
return bSuccess;
}
static bool GetCurrentUserSID(SID * * ppSid)
{
bool bSuccess = false;
// Pseudohandle so don't need to close it
HANDLE hProcess = ::GetCurrentProcess();
HANDLE hToken = NULL;
if (::OpenProcessToken(hProcess, TOKEN_QUERY, &hToken))
{
// Get the required size
DWORD tusize = 0;
GetTokenInformation(hToken, TokenUser, NULL, 0, &tusize);
TOKEN_USER* ptu = (TOKEN_USER*)new BYTE[tusize];
if (GetTokenInformation(hToken, TokenUser, (LPVOID)ptu, tusize, &tusize))
{
bSuccess = CopySid(ppSid, (SID *)ptu->User.Sid);
}
CloseHandle(hToken);
delete [] ptu;
}
return bSuccess;
}
};
IMPLEMENT_LOG4CXX_OBJECT(NTEventLogAppender)
NTEventLogAppender::NTEventLogAppender() : hEventLog(NULL), pCurrentUserSID(NULL)
{
}
NTEventLogAppender::NTEventLogAppender(const LogString& server, const LogString& log, const LogString& source, const LayoutPtr& layout)
: server(server), log(log), source(source), hEventLog(NULL), pCurrentUserSID(NULL)
{
this->layout = layout;
Pool pool;
activateOptions(pool);
}
NTEventLogAppender::~NTEventLogAppender()
{
finalize();
}
void NTEventLogAppender::close()
{
if (hEventLog != NULL)
{
::DeregisterEventSource(hEventLog);
hEventLog = NULL;
}
if (pCurrentUserSID != NULL)
{
CCtUserSIDHelper::FreeSid((::SID*) pCurrentUserSID);
pCurrentUserSID = NULL;
}
}
void NTEventLogAppender::setOption(const LogString& option, const LogString& value)
{
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SERVER"), LOG4CXX_STR("server")))
{
server = value;
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOG"), LOG4CXX_STR("log")))
{
log = value;
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SOURCE"), LOG4CXX_STR("source")))
{
source = value;
}
else
{
AppenderSkeleton::setOption(option, value);
}
}
void NTEventLogAppender::activateOptions(Pool&)
{
if (source.empty())
{
LogLog::warn(
((LogString) LOG4CXX_STR("Source option not set for appender ["))
+ name + LOG4CXX_STR("]."));
return;
}
if (log.empty())
{
log = LOG4CXX_STR("Application");
}
close();
// current user security identifier
CCtUserSIDHelper::GetCurrentUserSID((::SID**) &pCurrentUserSID);
addRegistryInfo();
LOG4CXX_ENCODE_WCHAR(wsource, source);
LOG4CXX_ENCODE_WCHAR(wserver, server);
hEventLog = ::RegisterEventSourceW(
wserver.empty() ? NULL : wserver.c_str(),
wsource.c_str());
if (hEventLog == NULL) {
LogString msg(LOG4CXX_STR("Cannot register NT EventLog -- server: '"));
msg.append(server);
msg.append(LOG4CXX_STR("' source: '"));
msg.append(source);
LogLog::error(msg);
LogLog::error(getErrorString(LOG4CXX_STR("RegisterEventSource")));
}
}
void NTEventLogAppender::append(const LoggingEventPtr& event, Pool& p)
{
if (hEventLog == NULL)
{
LogLog::warn(LOG4CXX_STR("NT EventLog not opened."));
return;
}
LogString oss;
layout->format(oss, event, p);
wchar_t* msgs = Transcoder::wencode(oss, p);
BOOL bSuccess = ::ReportEventW(
hEventLog,
getEventType(event),
getEventCategory(event),
0x1000,
pCurrentUserSID,
1,
0,
(LPCWSTR*) &msgs,
NULL);
if (!bSuccess)
{
LogLog::error(getErrorString(LOG4CXX_STR("ReportEvent")));
}
}
/*
* Add this source with appropriate configuration keys to the registry.
*/
void NTEventLogAppender::addRegistryInfo()
{
DWORD disposition = 0;
::HKEY hkey = 0;
LogString subkey(LOG4CXX_STR("SYSTEM\\CurrentControlSet\\Services\\EventLog\\"));
subkey.append(log);
subkey.append(1, (logchar) 0x5C /* '\\' */);
subkey.append(source);
LOG4CXX_ENCODE_WCHAR(wsubkey, subkey);
long stat = RegCreateKeyExW(HKEY_LOCAL_MACHINE, wsubkey.c_str(), 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL,
&hkey, &disposition);
if (stat == ERROR_SUCCESS && disposition == REG_CREATED_NEW_KEY) {
HMODULE hmodule = GetModuleHandleW(L"log4cxx");
if (hmodule == NULL) {
hmodule = GetModuleHandleW(0);
}
wchar_t modpath[_MAX_PATH];
DWORD modlen = GetModuleFileNameW(hmodule, modpath, _MAX_PATH - 1);
if (modlen > 0) {
modpath[modlen] = 0;
RegSetValueExW(hkey, L"EventMessageFile", 0, REG_SZ,
(LPBYTE) modpath, wcslen(modpath) * sizeof(wchar_t));
RegSetValueExW(hkey, L"CategoryMessageFile", 0, REG_SZ,
(LPBYTE) modpath, wcslen(modpath) * sizeof(wchar_t));
DWORD typesSupported = 7;
DWORD categoryCount = 6;
RegSetValueExW(hkey, L"TypesSupported", 0, REG_DWORD,
(LPBYTE)&typesSupported, sizeof(DWORD));
RegSetValueExW(hkey, L"CategoryCount", 0, REG_DWORD,
(LPBYTE)&categoryCount, sizeof(DWORD));
}
}
RegCloseKey(hkey);
return;
}
WORD NTEventLogAppender::getEventType(const LoggingEventPtr& event)
{
int priority = event->getLevel()->toInt();
WORD type = EVENTLOG_SUCCESS;
if (priority >= Level::INFO_INT) {
type = EVENTLOG_INFORMATION_TYPE;
if (priority >= Level::WARN_INT) {
type = EVENTLOG_WARNING_TYPE;
if (priority >= Level::ERROR_INT) {
type = EVENTLOG_ERROR_TYPE;
}
}
}
return type;
}
WORD NTEventLogAppender::getEventCategory(const LoggingEventPtr& event)
{
int priority = event->getLevel()->toInt();
WORD category = 1;
if (priority >= Level::DEBUG_INT) {
category = 2;
if (priority >= Level::INFO_INT) {
category = 3;
if (priority >= Level::WARN_INT) {
category = 4;
if (priority >= Level::ERROR_INT) {
category = 5;
if (priority >= Level::FATAL_INT) {
category = 6;
}
}
}
}
}
return category;
}
LogString NTEventLogAppender::getErrorString(const LogString& function)
{
Pool p;
enum { MSGSIZE = 5000 };
wchar_t* lpMsgBuf = (wchar_t*) p.palloc(MSGSIZE * sizeof(wchar_t));
DWORD dw = GetLastError();
FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
lpMsgBuf,
MSGSIZE, NULL );
LogString msg(function);
msg.append(LOG4CXX_STR(" failed with error "));
StringHelper::toString((size_t) dw, p, msg);
msg.append(LOG4CXX_STR(": "));
Transcoder::decode(lpMsgBuf, msg);
return msg;
}
#endif // WIN32
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/config/propertysetter.h>
#include <log4cxx/helpers/object.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/spi/optionhandler.h>
#include <log4cxx/helpers/properties.h>
#include <log4cxx/appender.h>
#include <log4cxx/layout.h>
#include <log4cxx/helpers/pool.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
using namespace log4cxx::config;
PropertySetter::PropertySetter(const helpers::ObjectPtr& obj1) : obj(obj1)
{
}
void PropertySetter::setProperties(const helpers::ObjectPtr& obj,
helpers::Properties& properties,
const LogString& prefix,
Pool& p)
{
PropertySetter(obj).setProperties(properties, prefix, p);
}
void PropertySetter::setProperties(helpers::Properties& properties,
const LogString& prefix,
Pool& p)
{
int len = prefix.length();
std::vector<LogString> names = properties.propertyNames();
std::vector<LogString>::iterator it;
for (it = names.begin(); it != names.end(); it++)
{
LogString key = *it;
// handle only properties that start with the desired frefix.
if (key.find(prefix) == 0)
{
// ignore key if it contains dots after the prefix
if (key.find(0x2E /* '.' */, len + 1) != LogString::npos)
{
continue;
}
LogString value = OptionConverter::findAndSubst(key, properties);
key = key.substr(len);
if (key == LOG4CXX_STR("layout")
&& obj != 0
&& obj->instanceof(Appender::getStaticClass()))
{
continue;
}
setProperty(key, value, p);
}
}
activate(p);
}
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 PropertySetter::activate(Pool& p)
{
if (obj != 0 && obj->instanceof(OptionHandler::getStaticClass()))
{
OptionHandlerPtr(obj)->activateOptions(p);
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/propertyresourcebundle.h>
#include <log4cxx/helpers/exception.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/private/log4cxx_private.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(PropertyResourceBundle)
PropertyResourceBundle::PropertyResourceBundle(InputStreamPtr inStream)
{
properties.load(inStream);
}
LogString PropertyResourceBundle::getString(const LogString& key) const
{
LogString resource;
PropertyResourceBundlePtr resourceBundle(const_cast<PropertyResourceBundle*>(this));
do
{
resource = resourceBundle->properties.getProperty(key);
if (!resource.empty())
{
return resource;
}
resourceBundle = resourceBundle->parent;
}
while (resourceBundle != 0);
throw MissingResourceException(key);
#if LOG4CXX_RETURN_AFTER_THROW
return resource;
#endif
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/pattern/linelocationpatternconverter.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/spi/location/locationinfo.h>
#include <log4cxx/helpers/stringhelper.h>
using namespace log4cxx;
using namespace log4cxx::pattern;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(LineLocationPatternConverter)
LineLocationPatternConverter::LineLocationPatternConverter() :
LoggingEventPatternConverter(LOG4CXX_STR("Line"),
LOG4CXX_STR("line")) {
}
PatternConverterPtr LineLocationPatternConverter::newInstance(
const std::vector<LogString>& /* options */) {
static PatternConverterPtr instance(new LineLocationPatternConverter());
return instance;
}
void LineLocationPatternConverter::format(
const LoggingEventPtr& event,
LogString& toAppendTo,
Pool& p) const {
StringHelper::toString(
event->getLocationInformation().getLineNumber(),
p, toAppendTo);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/pattern/messagepatternconverter.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/spi/location/locationinfo.h>
using namespace log4cxx;
using namespace log4cxx::pattern;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(MessagePatternConverter)
MessagePatternConverter::MessagePatternConverter() :
LoggingEventPatternConverter(LOG4CXX_STR("Message"),
LOG4CXX_STR("message")) {
}
PatternConverterPtr MessagePatternConverter::newInstance(
const std::vector<LogString>& /* options */) {
static PatternConverterPtr def(new MessagePatternConverter());
return def;
}
void MessagePatternConverter::format(
const LoggingEventPtr& event,
LogString& toAppendTo,
Pool& /* p */) const {
toAppendTo.append(event->getRenderedMessage());
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/net/telnetappender.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/synchronized.h>
#include <apr_thread_proc.h>
#include <apr_atomic.h>
#include <apr_strings.h>
#include <log4cxx/helpers/charsetencoder.h>
#include <log4cxx/helpers/bytebuffer.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::net;
#if APR_HAS_THREADS
IMPLEMENT_LOG4CXX_OBJECT(TelnetAppender)
/** The default telnet server port */
const int TelnetAppender::DEFAULT_PORT = 23;
/** The maximum number of concurrent connections */
const int TelnetAppender::MAX_CONNECTIONS = 20;
TelnetAppender::TelnetAppender()
: port(DEFAULT_PORT), connections(MAX_CONNECTIONS),
encoding(LOG4CXX_STR("UTF-8")),
encoder(CharsetEncoder::getUTF8Encoder()),
serverSocket(NULL), sh()
{
synchronized sync(mutex);
activeConnections = 0;
}
TelnetAppender::~TelnetAppender()
{
finalize();
delete serverSocket;
}
void TelnetAppender::activateOptions(Pool& /* p */)
{
if (serverSocket == NULL) {
serverSocket = new ServerSocket(port);
serverSocket->setSoTimeout(1000);
}
sh.run(acceptConnections, this);
}
void TelnetAppender::setOption(const LogString& option,
const LogString& value)
{
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("PORT"), LOG4CXX_STR("port")))
{
setPort(OptionConverter::toInt(value, DEFAULT_PORT));
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ENCODING"), LOG4CXX_STR("encoding")))
{
setEncoding(value);
}
else
{
AppenderSkeleton::setOption(option, value);
}
}
LogString TelnetAppender::getEncoding() const {
synchronized sync(mutex);
return encoding;
}
void TelnetAppender::setEncoding(const LogString& value) {
synchronized sync(mutex);
encoder = CharsetEncoder::getEncoder(value);
encoding = value;
}
void TelnetAppender::close()
{
synchronized sync(mutex);
if (closed) return;
closed = true;
SocketPtr nullSocket;
for(ConnectionList::iterator iter = connections.begin();
iter != connections.end();
iter++) {
if (*iter != 0) {
(*iter)->close();
*iter = nullSocket;
}
}
if (serverSocket != NULL) {
try {
serverSocket->close();
} catch(Exception&) {
}
}
try {
sh.join();
} catch(Exception& ex) {
}
activeConnections = 0;
}
void TelnetAppender::write(ByteBuffer& buf) {
for (ConnectionList::iterator iter = connections.begin();
iter != connections.end();
iter++) {
if (*iter != 0) {
try {
ByteBuffer b(buf.current(), buf.remaining());
(*iter)->write(b);
} catch(Exception& ex) {
// The client has closed the connection, remove it from our list:
*iter = 0;
activeConnections--;
}
}
}
}
void TelnetAppender::writeStatus(const SocketPtr& socket, const LogString& msg, Pool& p) {
size_t bytesSize = msg.size() * 2;
char* bytes = p.pstralloc(bytesSize);
LogString::const_iterator msgIter(msg.begin());
ByteBuffer buf(bytes, bytesSize);
while(msgIter != msg.end()) {
encoder->encode(msg, msgIter, buf);
buf.flip();
socket->write(buf);
buf.clear();
}
}
void TelnetAppender::append(const spi::LoggingEventPtr& event, Pool& p)
{
size_t count = activeConnections;
if (count > 0) {
LogString msg;
this->layout->format(msg, event, pool);
msg.append(LOG4CXX_STR("\r\n"));
size_t bytesSize = msg.size() * 2;
char* bytes = p.pstralloc(bytesSize);
LogString::const_iterator msgIter(msg.begin());
ByteBuffer buf(bytes, bytesSize);
synchronized sync(this->mutex);
while(msgIter != msg.end()) {
log4cxx_status_t stat = encoder->encode(msg, msgIter, buf);
buf.flip();
write(buf);
buf.clear();
if (CharsetEncoder::isError(stat)) {
LogString unrepresented(1, 0x3F /* '?' */);
LogString::const_iterator unrepresentedIter(unrepresented.begin());
stat = encoder->encode(unrepresented, unrepresentedIter, buf);
buf.flip();
write(buf);
buf.clear();
msgIter++;
}
}
}
}
void* APR_THREAD_FUNC TelnetAppender::acceptConnections(apr_thread_t* /* thread */, void* data) {
TelnetAppender* pThis = (TelnetAppender*) data;
// main loop; is left when This->closed is != 0 after an accept()
while(true)
{
try
{
SocketPtr newClient = pThis->serverSocket->accept();
bool done = pThis->closed;
if (done) {
Pool p;
pThis->writeStatus(newClient, LOG4CXX_STR("Log closed.\r\n"), p);
newClient->close();
return NULL;
}
size_t count = pThis->activeConnections;
if (count >= pThis->connections.size()) {
Pool p;
pThis->writeStatus(newClient, LOG4CXX_STR("Too many connections.\r\n"), p);
newClient->close();
} else {
//
// find unoccupied connection
//
synchronized sync(pThis->mutex);
for(ConnectionList::iterator iter = pThis->connections.begin();
iter != pThis->connections.end();
iter++) {
if (*iter == NULL) {
*iter = newClient;
pThis->activeConnections++;
break;
}
}
Pool p;
LogString oss(LOG4CXX_STR("TelnetAppender v1.0 ("));
StringHelper::toString((int) count+1, p, oss);
oss += LOG4CXX_STR(" active connections)\r\n\r\n");
pThis->writeStatus(newClient, oss, p);
}
} catch(InterruptedIOException &e) {
if (pThis->closed) {
return NULL;
}
} catch(Exception& e) {
if (!pThis->closed) {
LogLog::error(LOG4CXX_STR("Encountered error while in SocketHandler loop."), e);
} else {
return NULL;
}
}
}
return NULL;
}
#endif
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define __STDC_CONSTANT_MACROS
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/cacheddateformat.h>
#include <apr_time.h>
#include <log4cxx/helpers/pool.h>
#include <limits>
#include <log4cxx/helpers/exception.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::pattern;
/**
* Supported digit set. If the wrapped DateFormat uses
* a different unit set, the millisecond pattern
* will not be recognized and duplicate requests
* will use the cache.
*/
const logchar CachedDateFormat::digits[] = { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0 };
/**
* Expected representation of first magic number.
*/
const logchar CachedDateFormat::magicString1[] = { 0x36, 0x35, 0x34, 0 };
/**
* Expected representation of second magic number.
*/
const logchar CachedDateFormat::magicString2[] = { 0x39, 0x38, 0x37, 0};
/**
* Expected representation of 0 milliseconds.
*/
const logchar CachedDateFormat::zeroString[] = { 0x30, 0x30, 0x30, 0 };
#undef min
/**
* Creates a new CachedDateFormat object.
* @param dateFormat Date format, may not be null.
* @param expiration maximum cached range in milliseconds.
* If the dateFormat is known to be incompatible with the
* caching algorithm, use a value of 0 to totally disable
* caching or 1 to only use cache for duplicate requests.
*/
CachedDateFormat::CachedDateFormat(const DateFormatPtr& dateFormat,
int expiration1) :
formatter(dateFormat),
millisecondStart(0),
slotBegin(std::numeric_limits<log4cxx_time_t>::min()),
cache(50, 0x20),
expiration(expiration1),
previousTime(std::numeric_limits<log4cxx_time_t>::min()) {
if (dateFormat == NULL) {
throw IllegalArgumentException(LOG4CXX_STR("dateFormat cannot be null"));
}
if (expiration1 < 0) {
throw IllegalArgumentException(LOG4CXX_STR("expiration must be non-negative"));
}
}
/**
* Finds start of millisecond field in formatted time.
* @param time long time, must be integral number of seconds
* @param formatted String corresponding formatted string
* @param formatter DateFormat date format
* @return int position in string of first digit of milliseconds,
* -1 indicates no millisecond field, -2 indicates unrecognized
* field (likely RelativeTimeDateFormat)
*/
int CachedDateFormat::findMillisecondStart(
log4cxx_time_t time, const LogString& formatted,
const DateFormatPtr& formatter,
Pool& pool) {
apr_time_t slotBegin = (time / 1000000) * 1000000;
if (slotBegin > time) {
slotBegin -= 1000000;
}
int millis = (int) (time - slotBegin)/1000;
int magic = magic1;
LogString magicString(magicString1);
if (millis == magic1) {
magic = magic2;
magicString = magicString2;
}
LogString plusMagic;
formatter->format(plusMagic, slotBegin + magic, pool);
/**
* If the string lengths differ then
* we can't use the cache except for duplicate requests.
*/
if (plusMagic.length() != formatted.length()) {
return UNRECOGNIZED_MILLISECONDS;
} else {
// find first difference between values
for (LogString::size_type i = 0; i < formatted.length(); i++) {
if (formatted[i] != plusMagic[i]) {
//
// determine the expected digits for the base time
const logchar abc[] = { 0x41, 0x42, 0x43, 0 };
LogString formattedMillis(abc);
millisecondFormat(millis, formattedMillis, 0);
LogString plusZero;
formatter->format(plusZero, slotBegin, pool);
// If the next 3 characters match the magic
// strings and the remaining fragments are identical
//
//
if (plusZero.length() == formatted.length()
&& regionMatches(magicString, 0, plusMagic, i, magicString.length())
&& regionMatches(formattedMillis, 0, formatted, i, magicString.length())
&& regionMatches(zeroString, 0, plusZero, i, 3)
&& (formatted.length() == i + 3
|| plusZero.compare(i + 3,
LogString::npos, plusMagic, i+3, LogString::npos) == 0)) {
return i;
} else {
return UNRECOGNIZED_MILLISECONDS;
}
}
}
}
return NO_MILLISECONDS;
}
/**
* Formats a millisecond count into a date/time string.
*
* @param now Number of milliseconds after midnight 1 Jan 1970 GMT.
* @param sbuf the string buffer to write to
*/
void CachedDateFormat::format(LogString& buf, log4cxx_time_t now, Pool& p) const {
//
// If the current requested time is identical to the previously
// requested time, then append the cache contents.
//
if (now == previousTime) {
buf.append(cache);
return;
}
//
// If millisecond pattern was not unrecognized
// (that is if it was found or milliseconds did not appear)
//
if (millisecondStart != UNRECOGNIZED_MILLISECONDS) {
// Check if the cache is still valid.
// If the requested time is within the same integral second
// as the last request and a shorter expiration was not requested.
if (now < slotBegin + expiration
&& now >= slotBegin
&& now < slotBegin + 1000000L) {
//
// if there was a millisecond field then update it
//
if (millisecondStart >= 0 ) {
millisecondFormat((int) ((now - slotBegin)/1000), cache, millisecondStart);
}
//
// update the previously requested time
// (the slot begin should be unchanged)
previousTime = now;
buf.append(cache);
return;
}
}
//
// could not use previous value.
// Call underlying formatter to format date.
cache.erase(cache.begin(), cache.end());
formatter->format(cache, now, p);
buf.append(cache);
previousTime = now;
slotBegin = (previousTime / 1000000) * 1000000;
if (slotBegin > previousTime) {
slotBegin -= 1000000;
}
//
// if the milliseconds field was previous found
// then reevaluate in case it moved.
//
if (millisecondStart >= 0) {
millisecondStart = findMillisecondStart(now, cache, formatter, p);
}
}
/**
* Formats a count of milliseconds (0-999) into a numeric representation.
* @param millis Millisecond coun between 0 and 999.
* @buf String buffer, may not be null.
* @offset Starting position in buffer, the length of the
* buffer must be at least offset + 3.
*/
void CachedDateFormat::millisecondFormat(int millis,
LogString& buf,
int offset) {
buf[offset] = digits[ millis / 100];
buf[offset + 1] = digits[(millis / 10) % 10];
buf[offset + 2] = digits[millis % 10];
}
/**
* Set timezone.
*
* @remarks Setting the timezone using getCalendar().setTimeZone()
* will likely cause caching to misbehave.
* @param timeZone TimeZone new timezone
*/
void CachedDateFormat::setTimeZone(const TimeZonePtr& timeZone) {
formatter->setTimeZone(timeZone);
previousTime = std::numeric_limits<log4cxx_time_t>::min();
slotBegin = std::numeric_limits<log4cxx_time_t>::min();
}
void CachedDateFormat::numberFormat(LogString& s, int n, Pool& p) const {
formatter->numberFormat(s, n, p);
}
/**
* 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;
}
/**
* Tests if two string regions are equal.
* @param target target string.
* @param toffset character position in target to start comparison.
* @param other other string.
* @param ooffset character position in other to start comparison.
* @param len length of region.
* @return true if regions are equal.
*/
bool CachedDateFormat::regionMatches(
const LogString& target,
size_t toffset,
const LogString& other,
size_t ooffset,
size_t len) {
return target.compare(toffset, len, other, ooffset, len) == 0;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/threadspecificdata.h>
#include <log4cxx/helpers/exception.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/helpers/aprinitializer.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
ThreadSpecificData::ThreadSpecificData()
: ndcStack(), mdcMap() {
}
ThreadSpecificData::~ThreadSpecificData() {
}
log4cxx::NDC::Stack& ThreadSpecificData::getStack() {
return ndcStack;
}
log4cxx::MDC::Map& ThreadSpecificData::getMap() {
return mdcMap;
}
ThreadSpecificData& ThreadSpecificData::getDataNoThreads() {
static ThreadSpecificData noThreadData;
return noThreadData;
}
ThreadSpecificData* ThreadSpecificData::getCurrentData() {
#if APR_HAS_THREADS
void* pData = NULL;
apr_threadkey_private_get(&pData, APRInitializer::getTlsKey());
return (ThreadSpecificData*) pData;
#else
return &getDataNoThreads();
#endif
}
void ThreadSpecificData::recycle() {
#if APR_HAS_THREADS
if(ndcStack.empty() && mdcMap.empty()) {
void* pData = NULL;
apr_status_t stat = apr_threadkey_private_get(&pData, APRInitializer::getTlsKey());
if (stat == APR_SUCCESS && pData == this) {
stat = apr_threadkey_private_set(0, APRInitializer::getTlsKey());
if (stat == APR_SUCCESS) {
delete this;
}
}
}
#endif
}
void ThreadSpecificData::put(const LogString& key, const LogString& val) {
ThreadSpecificData* data = getCurrentData();
if (data == 0) {
data = createCurrentData();
}
if (data != 0) {
data->getMap().insert(log4cxx::MDC::Map::value_type(key, val));
}
}
void ThreadSpecificData::push(const LogString& val) {
ThreadSpecificData* data = getCurrentData();
if (data == 0) {
data = createCurrentData();
}
if (data != 0) {
NDC::Stack& stack = data->getStack();
if(stack.empty()) {
stack.push(NDC::DiagnosticContext(val, val));
} else {
LogString fullMessage(stack.top().second);
fullMessage.append(1, (logchar) 0x20);
fullMessage.append(val);
stack.push(NDC::DiagnosticContext(val, fullMessage));
}
}
}
void ThreadSpecificData::inherit(const NDC::Stack& src) {
ThreadSpecificData* data = getCurrentData();
if (data == 0) {
data = createCurrentData();
}
if (data != 0) {
data->getStack() = src;
}
}
ThreadSpecificData* ThreadSpecificData::createCurrentData() {
#if APR_HAS_THREADS
ThreadSpecificData* newData = new ThreadSpecificData();
apr_status_t stat = apr_threadkey_private_set(newData, APRInitializer::getTlsKey());
if (stat != APR_SUCCESS) {
delete newData;
newData = NULL;
}
return newData;
#else
return 0;
#endif
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/appender.h>
#include <log4cxx/logger.h>
#include <log4cxx/helpers/onlyonceerrorhandler.h>
#include <log4cxx/helpers/loglog.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
IMPLEMENT_LOG4CXX_OBJECT(OnlyOnceErrorHandler)
OnlyOnceErrorHandler::OnlyOnceErrorHandler() :
WARN_PREFIX(LOG4CXX_STR("log4cxx warning: ")),
ERROR_PREFIX(LOG4CXX_STR("log4cxx error: ")), firstTime(true)
{
}
void OnlyOnceErrorHandler::addRef() const {
ObjectImpl::addRef();
}
void OnlyOnceErrorHandler::releaseRef() const {
ObjectImpl::releaseRef();
}
void OnlyOnceErrorHandler::setLogger(const LoggerPtr&)
{
}
void OnlyOnceErrorHandler::activateOptions(Pool&)
{
}
void OnlyOnceErrorHandler::setOption(const LogString&, const LogString&)
{
}
void OnlyOnceErrorHandler::error(const LogString& message, const std::exception& e,
int) const
{
if(firstTime)
{
LogLog::error(message, e);
firstTime = false;
}
}
void OnlyOnceErrorHandler::error(const LogString& message, const std::exception& e,
int errorCode, const log4cxx::spi::LoggingEventPtr&) const
{
error(message, e, errorCode);
}
void OnlyOnceErrorHandler::error(const LogString& message) const
{
if(firstTime)
{
LogLog::error(message);
firstTime = false;
}
}
void OnlyOnceErrorHandler::setAppender(const AppenderPtr&)
{
}
void OnlyOnceErrorHandler::setBackupAppender(const AppenderPtr&)
{
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/pattern/loggingeventpatternconverter.h>
#include <log4cxx/spi/loggingevent.h>
using namespace log4cxx;
using namespace log4cxx::pattern;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(LoggingEventPatternConverter)
LoggingEventPatternConverter::LoggingEventPatternConverter(
const LogString& name1, const LogString& style1) : PatternConverter(name1, style1) {
}
void LoggingEventPatternConverter::format(const ObjectPtr& obj,
LogString& output,
log4cxx::helpers::Pool& p) const {
LoggingEventPtr le(obj);
if (le != NULL) {
format(le, output, p);
}
}
bool LoggingEventPatternConverter::handlesThrowable() const {
return false;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/systemoutwriter.h>
#include <log4cxx/helpers/transcoder.h>
#include <stdio.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/private/log4cxx_private.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(SystemOutWriter)
SystemOutWriter::SystemOutWriter() {
}
SystemOutWriter::~SystemOutWriter() {
}
void SystemOutWriter::close(Pool& /* p */ ) {
}
void SystemOutWriter::flush(Pool& /* p */ ) {
flush();
}
void SystemOutWriter::write(const LogString& str, Pool& /* p */ ) {
write(str);
}
bool SystemOutWriter::isWide() {
#if LOG4CXX_FORCE_WIDE_CONSOLE
return true;
#elif LOG4CXX_FORCE_BYTE_CONSOLE || !LOG4CXX_HAS_FWIDE
return false;
#else
return fwide(stdout, 0) > 0;
#endif
}
void SystemOutWriter::write(const LogString& str) {
#if LOG4CXX_WCHAR_T_API
if (isWide()) {
LOG4CXX_ENCODE_WCHAR(msg, str);
fputws(msg.c_str(), stdout);
return;
}
#endif
LOG4CXX_ENCODE_CHAR(msg, str);
fputs(msg.c_str(), stdout);
}
void SystemOutWriter::flush() {
fflush(stdout);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/spi/location/locationinfo.h>
#include <log4cxx/helpers/objectoutputstream.h>
#include <log4cxx/helpers/pool.h>
#include "apr_pools.h"
#include "apr_strings.h"
using namespace ::log4cxx::spi;
using namespace log4cxx::helpers;
/**
When location information is not available the constant
<code>NA</code> is returned. Current value of this string
constant is <b>?</b>. */
const char* const LocationInfo::NA = "?";
const char* const LocationInfo::NA_METHOD = "?::?";
const LocationInfo& LocationInfo::getLocationUnavailable() {
static const LocationInfo unavailable;
return unavailable;
}
/**
* Constructor.
* @remarks Used by LOG4CXX_LOCATION to generate
* location info for current code site
*/
LocationInfo::LocationInfo( const char * const fileName1,
const char * const methodName1,
int lineNumber1 )
: lineNumber( lineNumber1 ),
fileName( fileName1 ),
methodName( methodName1 ) {
}
/**
* Default constructor.
*/
LocationInfo::LocationInfo()
: lineNumber( -1 ),
fileName(LocationInfo::NA),
methodName(LocationInfo::NA_METHOD) {
}
/**
* Copy constructor.
* @param src source location
*/
LocationInfo::LocationInfo( const LocationInfo & src )
: lineNumber( src.lineNumber ),
fileName( src.fileName ),
methodName( src.methodName ) {
}
/**
* Assignment operator.
* @param src source location
*/
LocationInfo & LocationInfo::operator = ( const LocationInfo & src )
{
fileName = src.fileName;
methodName = src.methodName;
lineNumber = src.lineNumber;
return * this;
}
/**
* Resets location info to default state.
*/
void LocationInfo::clear() {
fileName = NA;
methodName = NA_METHOD;
lineNumber = -1;
}
/**
* Return the file name of the caller.
* @returns file name, may be null.
*/
const char * LocationInfo::getFileName() const
{
return fileName;
}
/**
* Returns the line number of the caller.
* @returns line number, -1 if not available.
*/
int LocationInfo::getLineNumber() const
{
return lineNumber;
}
/** Returns the method name of the caller. */
const std::string LocationInfo::getMethodName() const
{
std::string tmp(methodName);
size_t colonPos = tmp.find("::");
if (colonPos != std::string::npos) {
tmp.erase(0, colonPos + 2);
} else {
size_t spacePos = tmp.find(' ');
if (spacePos != std::string::npos) {
tmp.erase(0, spacePos + 1);
}
}
size_t parenPos = tmp.find('(');
if (parenPos != std::string::npos) {
tmp.erase(parenPos);
}
return tmp;
}
const std::string LocationInfo::getClassName() const {
std::string tmp(methodName);
size_t colonPos = tmp.find("::");
if (colonPos != std::string::npos) {
tmp.erase(colonPos);
size_t spacePos = tmp.find_last_of(' ');
if (spacePos != std::string::npos) {
tmp.erase(0, spacePos + 1);
}
return tmp;
}
tmp.erase(0, tmp.length() );
return tmp;
}
void LocationInfo::write(ObjectOutputStream& os, Pool& p) const {
if (lineNumber == -1 && fileName == NA && methodName == NA_METHOD) {
os.writeNull(p);
} else {
char prolog[] = {
0x72, 0x00, 0x21, 0x6F, 0x72, 0x67, 0x2E,
0x61, 0x70, 0x61, 0x63, 0x68, 0x65, 0x2E, 0x6C,
0x6F, 0x67, 0x34, 0x6A, 0x2E, 0x73, 0x70, 0x69,
0x2E, 0x4C, 0x6F, 0x63, 0x61, 0x74, 0x69, 0x6F,
0x6E, 0x49, 0x6E, 0x66, 0x6F, 0xED, 0x99, 0xBB,
0xE1, 0x4A, 0x91, 0xA5, 0x7C, 0x02, 0x00, 0x01,
0x4C, 0x00, 0x08, 0x66, 0x75, 0x6C, 0x6C, 0x49,
0x6E, 0x66, 0x6F,
0x74, 0x00, 0x12, 0x4C, 0x6A,
0x61, 0x76, 0x61, 0x2F, 0x6C, 0x61, 0x6E, 0x67,
0x2F, 0x53, 0x74, 0x72, 0x69, 0x6E, 0x67, 0x3B,
0x78, 0x70 };
os.writeProlog("org.apache.log4j.spi.LocationInfo", 2, prolog, sizeof(prolog), p);
char* line = p.itoa(lineNumber);
//
// construct Java-like fullInfo (replace "::" with ".")
//
std::string fullInfo(methodName);
size_t openParen = fullInfo.find('(');
if (openParen != std::string::npos) {
size_t space = fullInfo.find(' ');
if (space != std::string::npos && space < openParen) {
fullInfo.erase(0, space + 1);
}
}
openParen = fullInfo.find('(');
if (openParen != std::string::npos) {
size_t classSep = fullInfo.rfind("::", openParen);
if (classSep != std::string::npos) {
fullInfo.replace(classSep, 2, ".");
} else {
fullInfo.insert(0, ".");
}
}
fullInfo.append(1, '(');
fullInfo.append(fileName);
fullInfo.append(1, ':');
fullInfo.append(line);
fullInfo.append(1, ')');
os.writeUTFString(fullInfo, p);
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/rolling/action.h>
#include <log4cxx/helpers/synchronized.h>
using namespace log4cxx;
using namespace log4cxx::rolling;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(Action)
Action::Action() :
complete(false),
interrupted(false),
pool(),
mutex(pool) {
}
Action::~Action() {
}
/**
* {@inheritDoc}
*/
void Action::run(log4cxx::helpers::Pool& pool1) {
synchronized sync(mutex);
if (!interrupted) {
try {
execute(pool1);
} catch(std::exception& ex) {
reportException(ex);
}
complete = true;
interrupted = true;
}
}
/**
* {@inheritDoc}
*/
void Action::close() {
synchronized sync(mutex);
interrupted = true;
}
/**
* Tests if the action is complete.
* @return true if action is complete.
*/
bool Action::isComplete() const {
return complete;
}
/**
* Capture exception.
*
* @param ex exception.
*/
void Action::reportException(const std::exception& /* ex */) {
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/pattern/formattinginfo.h>
#include <limits.h>
using namespace log4cxx;
using namespace log4cxx::pattern;
IMPLEMENT_LOG4CXX_OBJECT(FormattingInfo)
/**
* Creates new instance.
* @param leftAlign left align if true.
* @param minLength minimum length.
* @param maxLength maximum length.
*/
FormattingInfo::FormattingInfo(
const bool leftAlign1, const int minLength1, const int maxLength1) :
minLength(minLength1),
maxLength(maxLength1),
leftAlign(leftAlign1) {
}
/**
* Gets default instance.
* @return default instance.
*/
FormattingInfoPtr FormattingInfo::getDefault() {
static FormattingInfoPtr def(new FormattingInfo(false, 0, INT_MAX));
return def;
}
/**
* Adjust the content of the buffer based on the specified lengths and alignment.
*
* @param fieldStart start of field in buffer.
* @param buffer buffer to be modified.
*/
void FormattingInfo::format(const int fieldStart, LogString& buffer) const {
int rawLength = buffer.length() - fieldStart;
if (rawLength > maxLength) {
buffer.erase(buffer.begin() + fieldStart,
buffer.begin() + fieldStart + (rawLength - maxLength));
} else if (rawLength < minLength) {
if (leftAlign) {
buffer.append(minLength - rawLength, (logchar) 0x20 /* ' ' */);
} else {
buffer.insert(fieldStart, minLength - rawLength, 0x20 /* ' ' */);
}
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/file.h>
#include <apr_file_io.h>
#include <apr_file_info.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/helpers/pool.h>
#include <assert.h>
#include <log4cxx/helpers/exception.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
File::File() {
}
template<class S>
static LogString decodeLS(const S* src) {
LogString dst;
if (src != 0) {
Transcoder::decode(src, dst);
}
return dst;
}
template<class S>
static LogString decodeLS(const std::basic_string<S>& src) {
LogString dst;
Transcoder::decode(src, dst);
return dst;
}
File::File(const std::string& name1)
: path(decodeLS(name1)) {
}
File::File(const char* name1)
: path(decodeLS(name1)) {
}
#if LOG4CXX_WCHAR_T_API
File::File(const std::wstring& name1)
: path(decodeLS(name1)) {
}
File::File(const wchar_t* name1)
: path(decodeLS(name1)) {
}
#endif
#if LOG4CXX_UNICHAR_API
File::File(const std::basic_string<UniChar>& name1)
: path(decodeLS(name1)) {
}
File::File(const UniChar* name1)
: path(decodeLS(name1)) {
}
#endif
#if LOG4CXX_CFSTRING_API
File::File(const CFStringRef& name1)
: path(decodeLS(name1)) {
}
#endif
File::File(const File& src)
: path(src.path) {
}
File& File::operator=(const File& src) {
if (this == &src) return *this;
path.assign(src.path);
return *this;
}
File::~File() {
}
LogString File::getPath() const {
return path;
}
File& File::setPath(const LogString& newName) {
path.assign(newName);
return *this;
}
LogString File::getName() const {
const logchar slashes[] = { 0x2F, 0x5C, 0 };
size_t lastSlash = path.find_last_of(slashes);
if (lastSlash != LogString::npos) {
return path.substr(lastSlash+1);
}
return path;
}
char* File::getPath(Pool& p) const {
int style = APR_FILEPATH_ENCODING_UNKNOWN;
apr_filepath_encoding(&style, p.getAPRPool());
char* retval = NULL;
if (style == APR_FILEPATH_ENCODING_UTF8) {
retval = Transcoder::encodeUTF8(path, p);
} else {
retval = Transcoder::encode(path, p);
}
return retval;
}
log4cxx_status_t File::open(apr_file_t** file, int flags,
int perm, Pool& p) const {
return apr_file_open(file, getPath(p), flags, perm, p.getAPRPool());
}
bool File::exists(Pool& p) const {
apr_finfo_t finfo;
apr_status_t rv = apr_stat(&finfo, getPath(p),
0, p.getAPRPool());
return rv == APR_SUCCESS;
}
char* File::convertBackSlashes(char* src) {
for(char* c = src; *c != 0; c++) {
if(*c == '\\') {
*c = '/';
}
}
return src;
}
bool File::deleteFile(Pool& p) const {
apr_status_t rv = apr_file_remove(convertBackSlashes(getPath(p)),
p.getAPRPool());
return rv == APR_SUCCESS;
}
bool File::renameTo(const File& dest, Pool& p) const {
apr_status_t rv = apr_file_rename(convertBackSlashes(getPath(p)),
convertBackSlashes(dest.getPath(p)),
p.getAPRPool());
return rv == APR_SUCCESS;
}
size_t File::length(Pool& pool) const {
apr_finfo_t finfo;
apr_status_t rv = apr_stat(&finfo, getPath(pool),
APR_FINFO_SIZE, pool.getAPRPool());
if (rv == APR_SUCCESS) {
return (size_t) finfo.size;
}
return 0;
}
log4cxx_time_t File::lastModified(Pool& pool) const {
apr_finfo_t finfo;
apr_status_t rv = apr_stat(&finfo, getPath(pool),
APR_FINFO_MTIME, pool.getAPRPool());
if (rv == APR_SUCCESS) {
return finfo.mtime;
}
return 0;
}
std::vector<LogString> File::list(Pool& p) const {
apr_dir_t *dir;
apr_finfo_t entry;
std::vector<LogString> filenames;
apr_status_t stat = apr_dir_open(&dir,
convertBackSlashes(getPath(p)),
p.getAPRPool());
if(stat == APR_SUCCESS) {
int style = APR_FILEPATH_ENCODING_UNKNOWN;
apr_filepath_encoding(&style, p.getAPRPool());
stat = apr_dir_read(&entry, APR_FINFO_DIRENT, dir);
while(stat == APR_SUCCESS) {
if (entry.name != NULL) {
LogString filename;
if(style == APR_FILEPATH_ENCODING_UTF8) {
Transcoder::decodeUTF8(entry.name, filename);
} else {
Transcoder::decode(entry.name, filename);
}
filenames.push_back(filename);
}
stat = apr_dir_read(&entry, APR_FINFO_DIRENT, dir);
}
stat = apr_dir_close(dir);
}
return filenames;
}
LogString File::getParent(Pool&) const {
LogString::size_type slashPos = path.rfind(LOG4CXX_STR('/'));
LogString::size_type backPos = path.rfind(LOG4CXX_STR('\\'));
if (slashPos == LogString::npos) {
slashPos = backPos;
} else {
if (backPos != LogString::npos && backPos > slashPos) {
slashPos = backPos;
}
}
LogString parent;
if (slashPos != LogString::npos && slashPos > 0) {
parent.assign(path, 0, slashPos);
}
return parent;
}
bool File::mkdirs(Pool& p) const {
apr_status_t stat = apr_dir_make_recursive(convertBackSlashes(getPath(p)),
APR_OS_DEFAULT, p.getAPRPool());
return stat == APR_SUCCESS;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/helpers/objectptr.h>
#include <log4cxx/helpers/exception.h>
#include <apr_atomic.h>
using namespace log4cxx::helpers;
ObjectPtrBase::ObjectPtrBase() {
}
ObjectPtrBase::~ObjectPtrBase() {
}
void ObjectPtrBase::checkNull(const int& null) {
if (null != 0) {
throw IllegalArgumentException(LOG4CXX_STR("Attempt to set pointer to a non-zero numeric value."));
}
}
void* ObjectPtrBase::exchange(void** destination, void* newValue) {
#if _WIN32 && (!defined(_MSC_VER) || _MSC_VER >= 1300)
return InterlockedExchangePointer(destination, newValue);
#elif APR_SIZEOF_VOIDP == 4
return (void*) apr_atomic_xchg32((volatile apr_uint32_t*) destination,
(apr_uint32_t) newValue);
#else
void* oldValue = *destination;
*destination = newValue;
return oldValue;
#endif
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/spi/defaultrepositoryselector.h>
using namespace log4cxx;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
DefaultRepositorySelector::DefaultRepositorySelector(const LoggerRepositoryPtr& repository1)
: repository(repository1) {
}
void DefaultRepositorySelector::addRef() const {
ObjectImpl::addRef();
}
void DefaultRepositorySelector::releaseRef() const {
ObjectImpl::releaseRef();
}
LoggerRepositoryPtr& DefaultRepositorySelector::getLoggerRepository() {
return repository;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/pattern/classnamepatternconverter.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/spi/location/locationinfo.h>
using namespace log4cxx;
using namespace log4cxx::pattern;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(ClassNamePatternConverter)
ClassNamePatternConverter::ClassNamePatternConverter(
const std::vector<LogString>& options) :
NamePatternConverter(LOG4CXX_STR("Class Name"),
LOG4CXX_STR("class name"), options) {
}
PatternConverterPtr ClassNamePatternConverter::newInstance(
const std::vector<LogString>& options) {
if (options.size() == 0) {
static PatternConverterPtr def(new ClassNamePatternConverter(options));
return def;
}
return new ClassNamePatternConverter(options);
}
void ClassNamePatternConverter::format(
const LoggingEventPtr& event,
LogString& toAppendTo,
Pool& /* p */) const {
int initialLength = toAppendTo.length();
append(toAppendTo, event->getLocationInformation().getClassName());
abbreviate(initialLength, toAppendTo);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/xml/xmllayout.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/level.h>
#include <log4cxx/helpers/transform.h>
#include <log4cxx/helpers/iso8601dateformat.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/ndc.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
using namespace log4cxx::xml;
IMPLEMENT_LOG4CXX_OBJECT(XMLLayout)
XMLLayout::XMLLayout()
: locationInfo(false), properties(false)
{
}
void XMLLayout::setOption(const LogString& option,
const LogString& value)
{
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOCATIONINFO"), LOG4CXX_STR("locationinfo")))
{
setLocationInfo(OptionConverter::toBoolean(value, false));
}
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("PROPERTIES"), LOG4CXX_STR("properties")))
{
setProperties(OptionConverter::toBoolean(value, false));
}
}
void XMLLayout::format(LogString& output,
const spi::LoggingEventPtr& event,
Pool& p) const
{
output.append(LOG4CXX_STR("<log4j:event logger=\""));
Transform::appendEscapingTags(output, event->getLoggerName());
output.append(LOG4CXX_STR("\" timestamp=\""));
StringHelper::toString(event->getTimeStamp()/1000L, p, output);
output.append(LOG4CXX_STR("\" level=\""));
Transform::appendEscapingTags(output, event->getLevel()->toString());
output.append(LOG4CXX_STR("\" thread=\""));
Transform::appendEscapingTags(output, event->getThreadName());
output.append(LOG4CXX_STR("\">"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_STR("<log4j:message><![CDATA["));
// Append the rendered message. Also make sure to escape any
// existing CDATA sections.
Transform::appendEscapingCDATA(output, event->getRenderedMessage());
output.append(LOG4CXX_STR("]]></log4j:message>"));
output.append(LOG4CXX_EOL);
LogString ndc;
if(event->getNDC(ndc)) {
output.append(LOG4CXX_STR("<log4j:NDC><![CDATA["));
Transform::appendEscapingCDATA(output, ndc);
output.append(LOG4CXX_STR("]]></log4j:NDC>"));
output.append(LOG4CXX_EOL);
}
if(locationInfo)
{
output.append(LOG4CXX_STR("<log4j:locationInfo class=\""));
const LocationInfo& locInfo = event->getLocationInformation();
LOG4CXX_DECODE_CHAR(className, locInfo.getClassName());
Transform::appendEscapingTags(output, className);
output.append(LOG4CXX_STR("\" method=\""));
LOG4CXX_DECODE_CHAR(method, locInfo.getMethodName());
Transform::appendEscapingTags(output, method);
output.append(LOG4CXX_STR("\" file=\""));
LOG4CXX_DECODE_CHAR(fileName, locInfo.getFileName());
Transform::appendEscapingTags(output, fileName);
output.append(LOG4CXX_STR("\" line=\""));
StringHelper::toString(locInfo.getLineNumber(), p, output);
output.append(LOG4CXX_STR("\"/>"));
output.append(LOG4CXX_EOL);
}
if (properties) {
LoggingEvent::KeySet propertySet(event->getPropertyKeySet());
LoggingEvent::KeySet keySet(event->getMDCKeySet());
if (!(keySet.empty() && propertySet.empty())) {
output.append(LOG4CXX_STR("<log4j:properties>"));
output.append(LOG4CXX_EOL);
for (LoggingEvent::KeySet::const_iterator i = keySet.begin();
i != keySet.end();
i++) {
LogString key(*i);
LogString value;
if(event->getMDC(key, value)) {
output.append(LOG4CXX_STR("<log4j:data name=\""));
Transform::appendEscapingTags(output, key);
output.append(LOG4CXX_STR("\" value=\""));
Transform::appendEscapingTags(output, value);
output.append(LOG4CXX_STR("\"/>"));
output.append(LOG4CXX_EOL);
}
}
for (LoggingEvent::KeySet::const_iterator i2 = propertySet.begin();
i2 != propertySet.end();
i2++) {
LogString key(*i2);
LogString value;
if(event->getProperty(key, value)) {
output.append(LOG4CXX_STR("<log4j:data name=\""));
Transform::appendEscapingTags(output, key);
output.append(LOG4CXX_STR("\" value=\""));
Transform::appendEscapingTags(output, value);
output.append(LOG4CXX_STR("\"/>"));
output.append(LOG4CXX_EOL);
}
}
output.append(LOG4CXX_STR("</log4j:properties>"));
output.append(LOG4CXX_EOL);
}
}
output.append(LOG4CXX_STR("</log4j:event>"));
output.append(LOG4CXX_EOL);
output.append(LOG4CXX_EOL);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/filter/levelrangefilter.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/level.h>
using namespace log4cxx;
using namespace log4cxx::filter;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(LevelRangeFilter)
LevelRangeFilter::LevelRangeFilter()
: acceptOnMatch(true), levelMin(Level::getAll()), levelMax(Level::getOff())
{
}
void LevelRangeFilter::setOption(const LogString& option,
const LogString& value)
{
if (StringHelper::equalsIgnoreCase(option,
LOG4CXX_STR("LEVELMIN"), LOG4CXX_STR("levelmin")))
{
levelMin = OptionConverter::toLevel(value, levelMin);
}
else if (StringHelper::equalsIgnoreCase(option,
LOG4CXX_STR("LEVELMAX"), LOG4CXX_STR("levelmax")))
{
levelMax = OptionConverter::toLevel(value, levelMax);
}
else if (StringHelper::equalsIgnoreCase(option,
LOG4CXX_STR("ACCEPTONMATCH"), LOG4CXX_STR("acceptonmatch")))
{
acceptOnMatch = OptionConverter::toBoolean(value, acceptOnMatch);
}
}
Filter::FilterDecision LevelRangeFilter::decide(
const spi::LoggingEventPtr& event) const
{
if (levelMin != 0 && !event->getLevel()->isGreaterOrEqual(levelMin))
{
// level of event is less than minimum
return Filter::DENY;
}
if (levelMax != 0 && event->getLevel()->toInt() > levelMax->toInt())
{
// level of event is greater than maximum
// Alas, there is no Level.isGreater method. and using
// a combo of isGreaterOrEqual && !Equal seems worse than
// checking the int values of the level objects..
return Filter::DENY;
}
if (acceptOnMatch)
{
// this filter set up to bypass later filters and always return
// accept if level in range
return Filter::ACCEPT;
}
else
{
// event is ok for this filter; allow later filters to have a look..
return Filter::NEUTRAL;
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/pattern/namepatternconverter.h>
#include <log4cxx/pattern/nameabbreviator.h>
#include <log4cxx/spi/loggingevent.h>
using namespace log4cxx;
using namespace log4cxx::pattern;
using namespace log4cxx::spi;
IMPLEMENT_LOG4CXX_OBJECT(NamePatternConverter)
NamePatternConverter::NamePatternConverter(
const LogString& name1,
const LogString& style1,
const std::vector<LogString>& options) :
LoggingEventPatternConverter(name1, style1),
abbreviator(getAbbreviator(options)) {
}
NameAbbreviatorPtr NamePatternConverter::getAbbreviator(
const std::vector<LogString>& options) {
if (options.size() > 0) {
return NameAbbreviator::getAbbreviator(options[0]);
}
return NameAbbreviator::getDefaultAbbreviator();
}
/**
* Abbreviate name in string buffer.
* @param nameStart starting position of name to abbreviate.
* @param buf string buffer containing name.
*/
void NamePatternConverter::abbreviate(int nameStart, LogString& buf) const {
abbreviator->abbreviate(nameStart, buf);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/asyncappender.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/spi/loggingevent.h>
#include <apr_thread_proc.h>
#include <apr_thread_mutex.h>
#include <apr_thread_cond.h>
#include <log4cxx/helpers/condition.h>
#include <log4cxx/helpers/synchronized.h>
#include <log4cxx/helpers/stringhelper.h>
#include <apr_atomic.h>
#include <log4cxx/helpers/optionconverter.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
IMPLEMENT_LOG4CXX_OBJECT(AsyncAppender)
AsyncAppender::AsyncAppender()
: AppenderSkeleton(),
buffer(),
bufferMutex(pool),
bufferNotFull(pool),
bufferNotEmpty(pool),
discardMap(new DiscardMap()),
bufferSize(DEFAULT_BUFFER_SIZE),
appenders(new AppenderAttachableImpl(pool)),
dispatcher(),
locationInfo(false),
blocking(true) {
#if APR_HAS_THREADS
dispatcher.run(dispatch, this);
#endif
}
AsyncAppender::~AsyncAppender()
{
finalize();
delete discardMap;
}
void AsyncAppender::addRef() const {
ObjectImpl::addRef();
}
void AsyncAppender::releaseRef() const {
ObjectImpl::releaseRef();
}
void AsyncAppender::addAppender(const AppenderPtr& newAppender)
{
synchronized sync(appenders->getMutex());
appenders->addAppender(newAppender);
}
void AsyncAppender::setOption(const LogString& option,
const LogString& value) {
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOCATIONINFO"), LOG4CXX_STR("locationinfo"))) {
setLocationInfo(OptionConverter::toBoolean(value, false));
}
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFERSIZE"), LOG4CXX_STR("buffersize"))) {
setBufferSize(OptionConverter::toInt(value, DEFAULT_BUFFER_SIZE));
}
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BLOCKING"), LOG4CXX_STR("blocking"))) {
setBlocking(OptionConverter::toBoolean(value, true));
} else {
AppenderSkeleton::setOption(option, value);
}
}
void AsyncAppender::append(const spi::LoggingEventPtr& event, Pool& p) {
#if APR_HAS_THREADS
//
// if dispatcher has died then
// append subsequent events synchronously
//
if (!dispatcher.isAlive() || bufferSize <= 0) {
synchronized sync(appenders->getMutex());
appenders->appendLoopOnAppenders(event, p);
return;
}
// Set the NDC and thread name for the calling thread as these
// LoggingEvent fields were not set at event creation time.
LogString ndcVal;
event->getNDC(ndcVal);
event->getThreadName();
// Get a copy of this thread's MDC.
event->getMDCCopy();
{
synchronized sync(bufferMutex);
while(true) {
int previousSize = buffer.size();
if (previousSize < bufferSize) {
buffer.push_back(event);
if (previousSize == 0) {
bufferNotEmpty.signalAll();
}
break;
}
//
// Following code is only reachable if buffer is full
//
//
// if blocking and thread is not already interrupted
// and not the dispatcher then
// wait for a buffer notification
bool discard = true;
if (blocking
&& !Thread::interrupted()
&& !dispatcher.isCurrentThread()) {
try {
bufferNotFull.await(bufferMutex);
discard = false;
} catch (InterruptedException& e) {
//
// reset interrupt status so
// calling code can see interrupt on
// their next wait or sleep.
Thread::currentThreadInterrupt();
}
}
//
// if blocking is false or thread has been interrupted
// add event to discard map.
//
if (discard) {
LogString loggerName = event->getLoggerName();
DiscardMap::iterator iter = discardMap->find(loggerName);
if (iter == discardMap->end()) {
DiscardSummary summary(event);
discardMap->insert(DiscardMap::value_type(loggerName, summary));
} else {
(*iter).second.add(event);
}
break;
}
}
}
#else
synchronized sync(appenders->getMutex());
appenders->appendLoopOnAppenders(event, p);
#endif
}
void AsyncAppender::close() {
{
synchronized sync(bufferMutex);
closed = true;
bufferNotEmpty.signalAll();
bufferNotFull.signalAll();
}
#if APR_HAS_THREADS
try {
dispatcher.join();
} catch(InterruptedException& e) {
Thread::currentThreadInterrupt();
LogLog::error(LOG4CXX_STR("Got an InterruptedException while waiting for the dispatcher to finish,"), e);
}
#endif
{
synchronized sync(appenders->getMutex());
AppenderList appenderList = appenders->getAllAppenders();
for (AppenderList::iterator iter = appenderList.begin();
iter != appenderList.end();
iter++) {
(*iter)->close();
}
}
}
AppenderList AsyncAppender::getAllAppenders() const
{
synchronized sync(appenders->getMutex());
return appenders->getAllAppenders();
}
AppenderPtr AsyncAppender::getAppender(const LogString& name) const
{
synchronized sync(appenders->getMutex());
return appenders->getAppender(name);
}
bool AsyncAppender::isAttached(const AppenderPtr& appender) const
{
synchronized sync(appenders->getMutex());
return appenders->isAttached(appender);
}
bool AsyncAppender::requiresLayout() const {
return false;
}
void AsyncAppender::removeAllAppenders()
{
synchronized sync(appenders->getMutex());
appenders->removeAllAppenders();
}
void AsyncAppender::removeAppender(const AppenderPtr& appender)
{
synchronized sync(appenders->getMutex());
appenders->removeAppender(appender);
}
void AsyncAppender::removeAppender(const LogString& name)
{
synchronized sync(appenders->getMutex());
appenders->removeAppender(name);
}
bool AsyncAppender::getLocationInfo() const {
return locationInfo;
}
void AsyncAppender::setLocationInfo(bool flag) {
locationInfo = flag;
}
void AsyncAppender::setBufferSize(int size)
{
if (size < 0) {
throw IllegalArgumentException(LOG4CXX_STR("size argument must be non-negative"));
}
synchronized sync(bufferMutex);
bufferSize = (size < 1) ? 1 : size;
bufferNotFull.signalAll();
}
int AsyncAppender::getBufferSize() const
{
return bufferSize;
}
void AsyncAppender::setBlocking(bool value) {
synchronized sync(bufferMutex);
blocking = value;
bufferNotFull.signalAll();
}
bool AsyncAppender::getBlocking() const {
return blocking;
}
AsyncAppender::DiscardSummary::DiscardSummary(const LoggingEventPtr& event) :
maxEvent(event), count(1) {
}
AsyncAppender::DiscardSummary::DiscardSummary(const DiscardSummary& src) :
maxEvent(src.maxEvent), count(src.count) {
}
AsyncAppender::DiscardSummary& AsyncAppender::DiscardSummary::operator=(const DiscardSummary& src) {
maxEvent = src.maxEvent;
count = src.count;
return *this;
}
void AsyncAppender::DiscardSummary::add(const LoggingEventPtr& event) {
if (event->getLevel()->toInt() > maxEvent->getLevel()->toInt()) {
maxEvent = event;
}
count++;
}
LoggingEventPtr AsyncAppender::DiscardSummary::createEvent(Pool& p) {
LogString msg(LOG4CXX_STR("Discarded "));
StringHelper::toString(count, p, msg);
msg.append(LOG4CXX_STR(" messages due to a full event buffer including: "));
msg.append(maxEvent->getMessage());
return new LoggingEvent(
maxEvent->getLoggerName(),
maxEvent->getLevel(),
msg,
LocationInfo::getLocationUnavailable());
}
#if APR_HAS_THREADS
void* LOG4CXX_THREAD_FUNC AsyncAppender::dispatch(apr_thread_t* thread, void* data) {
AsyncAppender* pThis = (AsyncAppender*) data;
bool isActive = true;
try {
while (isActive) {
//
// process events after lock on buffer is released.
//
Pool p;
LoggingEventList events;
{
synchronized sync(pThis->bufferMutex);
size_t bufferSize = pThis->buffer.size();
isActive = !pThis->closed;
while((bufferSize == 0) && isActive) {
pThis->bufferNotEmpty.await(pThis->bufferMutex);
bufferSize = pThis->buffer.size();
isActive = !pThis->closed;
}
for(LoggingEventList::iterator eventIter = pThis->buffer.begin();
eventIter != pThis->buffer.end();
eventIter++) {
events.push_back(*eventIter);
}
for(DiscardMap::iterator discardIter = pThis->discardMap->begin();
discardIter != pThis->discardMap->end();
discardIter++) {
events.push_back(discardIter->second.createEvent(p));
}
pThis->buffer.clear();
pThis->discardMap->clear();
pThis->bufferNotFull.signalAll();
}
for (LoggingEventList::iterator iter = events.begin();
iter != events.end();
iter++) {
synchronized sync(pThis->appenders->getMutex());
pThis->appenders->appendLoopOnAppenders(*iter, p);
}
}
} catch(InterruptedException& ex) {
Thread::currentThreadInterrupt();
} catch(...) {
}
return 0;
}
#endif
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/objectimpl.h>
#include <apr_atomic.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/helpers/aprinitializer.h>
using namespace log4cxx::helpers;
ObjectImpl::ObjectImpl() : ref( 0 )
{
log4cxx::helpers::APRInitializer::initialize();
}
ObjectImpl::~ObjectImpl()
{
}
void ObjectImpl::addRef() const
{
apr_atomic_inc32( & ref );
}
void ObjectImpl::releaseRef() const
{
if ( apr_atomic_dec32( & ref ) == 0 )
{
delete this;
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/rolling/timebasedrollingpolicy.h>
#include <log4cxx/pattern/filedatepatternconverter.h>
#include <log4cxx/helpers/date.h>
#include <log4cxx/rolling/filerenameaction.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/rolling/gzcompressaction.h>
#include <log4cxx/rolling/zipcompressaction.h>
#ifndef INT64_C
#define INT64_C(x) x ## LL
#endif
#include <apr_time.h>
using namespace log4cxx;
using namespace log4cxx::rolling;
using namespace log4cxx::helpers;
using namespace log4cxx::pattern;
IMPLEMENT_LOG4CXX_OBJECT(TimeBasedRollingPolicy)
TimeBasedRollingPolicy::TimeBasedRollingPolicy() {
}
void TimeBasedRollingPolicy::addRef() const {
TriggeringPolicy::addRef();
}
void TimeBasedRollingPolicy::releaseRef() const {
TriggeringPolicy::releaseRef();
}
void TimeBasedRollingPolicy::activateOptions(log4cxx::helpers::Pool& pool) {
// find out period from the filename pattern
if (getFileNamePattern().length() > 0) {
parseFileNamePattern();
} else {
LogLog::warn(
LOG4CXX_STR("The FileNamePattern option must be set before using TimeBasedRollingPolicy. "));
throw IllegalStateException();
}
PatternConverterPtr dtc(getDatePatternConverter());
if (dtc == NULL) {
throw IllegalStateException();
}
apr_time_t n = apr_time_now();
LogString buf;
ObjectPtr obj(new Date(n));
formatFileName(obj, buf, pool);
lastFileName = buf;
suffixLength = 0;
if (lastFileName.length() >= 3) {
if (lastFileName.compare(lastFileName.length() - 3, 3, LOG4CXX_STR(".gz")) == 0) {
suffixLength = 3;
} else if (lastFileName.length() >= 4 && lastFileName.compare(lastFileName.length() - 4, 4, LOG4CXX_STR(".zip")) == 0) {
suffixLength = 4;
}
}
}
#define RULES_PUT(spec, cls) \
specs.insert(PatternMap::value_type(LogString(LOG4CXX_STR(spec)), (PatternConstructor) cls ::newInstance))
log4cxx::pattern::PatternMap TimeBasedRollingPolicy::getFormatSpecifiers() const {
PatternMap specs;
RULES_PUT("d", FileDatePatternConverter);
RULES_PUT("date", FileDatePatternConverter);
return specs;
}
/**
* {@inheritDoc}
*/
RolloverDescriptionPtr TimeBasedRollingPolicy::initialize(
const LogString& currentActiveFile,
const bool append,
Pool& pool) {
apr_time_t n = apr_time_now();
nextCheck = ((n / APR_USEC_PER_SEC) + 1) * APR_USEC_PER_SEC;
LogString buf;
ObjectPtr obj(new Date(n));
formatFileName(obj, buf, pool);
lastFileName = buf;
ActionPtr noAction;
if (currentActiveFile.length() > 0) {
return new RolloverDescription(
currentActiveFile, append, noAction, noAction);
} else {
return new RolloverDescription(
lastFileName.substr(0, lastFileName.length() - suffixLength), append,
noAction, noAction);
}
}
RolloverDescriptionPtr TimeBasedRollingPolicy::rollover(
const LogString& currentActiveFile,
Pool& pool) {
apr_time_t n = apr_time_now();
nextCheck = ((n / APR_USEC_PER_SEC) + 1) * APR_USEC_PER_SEC;
LogString buf;
ObjectPtr obj(new Date(n));
formatFileName(obj, buf, pool);
LogString newFileName(buf);
//
// if file names haven't changed, no rollover
//
if (newFileName == lastFileName) {
RolloverDescriptionPtr desc;
return desc;
}
ActionPtr renameAction;
ActionPtr compressAction;
LogString lastBaseName(
lastFileName.substr(0, lastFileName.length() - suffixLength));
LogString nextActiveFile(
newFileName.substr(0, newFileName.length() - suffixLength));
//
// if currentActiveFile is not lastBaseName then
// active file name is not following file pattern
// and requires a rename plus maintaining the same name
if (currentActiveFile != lastBaseName) {
renameAction =
new FileRenameAction(
File().setPath(currentActiveFile), File().setPath(lastBaseName), true);
nextActiveFile = currentActiveFile;
}
if (suffixLength == 3) {
compressAction =
new GZCompressAction(
File().setPath(lastBaseName), File().setPath(lastFileName), true);
}
if (suffixLength == 4) {
compressAction =
new ZipCompressAction(
File().setPath(lastBaseName), File().setPath(lastFileName), true);
}
lastFileName = newFileName;
return new RolloverDescription(
nextActiveFile, false, renameAction, compressAction);
}
bool TimeBasedRollingPolicy::isTriggeringEvent(
Appender* /* appender */,
const log4cxx::spi::LoggingEventPtr& /* event */,
const LogString& /* filename */,
size_t /* fileLength */) {
return apr_time_now() > nextCheck;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/rolling/triggeringpolicy.h>
using namespace log4cxx;
using namespace log4cxx::rolling;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(TriggeringPolicy)
TriggeringPolicy::~TriggeringPolicy() {
}
void TriggeringPolicy::addRef() const {
ObjectImpl::addRef();
}
void TriggeringPolicy::releaseRef() const {
ObjectImpl::releaseRef();
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/date.h>
#ifndef INT64_C
#define INT64_C(x) x ## LL
#endif
#include <apr_time.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(Date)
Date::Date() : time(apr_time_now()) {
}
Date::Date(log4cxx_time_t t) : time(t) {
}
Date::~Date() {
}
log4cxx_time_t Date::getMicrosecondsPerDay() {
return APR_INT64_C(86400000000);
}
log4cxx_time_t Date::getMicrosecondsPerSecond() {
return APR_USEC_PER_SEC;
}
log4cxx_time_t Date::getNextSecond() const {
return ((time / APR_USEC_PER_SEC) + 1) * APR_USEC_PER_SEC;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/rollingfileappender.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/rolling/rollingfileappenderskeleton.h>
#include <log4cxx/rolling/sizebasedtriggeringpolicy.h>
#include <log4cxx/rolling/fixedwindowrollingpolicy.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
namespace log4cxx {
class ClassRollingFileAppender : public Class
{
public:
ClassRollingFileAppender() : helpers::Class() {}
virtual LogString getName() const {
return LOG4CXX_STR("org.apache.log4j.RollingFileAppender");
}
virtual ObjectPtr newInstance() const {
return new RollingFileAppender();
}
};
}
const log4cxx::helpers::Class& RollingFileAppender::getClass() const { return getStaticClass(); }
const log4cxx::helpers::Class& RollingFileAppender::getStaticClass() {
static ClassRollingFileAppender theClass;
return theClass;
}
const log4cxx::helpers::ClassRegistration& RollingFileAppender::registerClass() {
static log4cxx::helpers::ClassRegistration classReg(RollingFileAppender::getStaticClass);
return classReg;
}
namespace log4cxx { namespace classes {
const log4cxx::helpers::ClassRegistration& ObsoleteRollingFileAppenderRegistration =
RollingFileAppender::registerClass();
} }
RollingFileAppender::RollingFileAppender()
: maxFileSize(10*1024*1024), maxBackupIndex(1) {
}
RollingFileAppender::RollingFileAppender(
const LayoutPtr& layout,
const LogString& filename,
bool append)
: maxFileSize(10*1024*1024), maxBackupIndex(1) {
setLayout(layout);
setFile(filename);
setAppend(append);
Pool pool;
activateOptions(pool);
}
RollingFileAppender::RollingFileAppender(const LayoutPtr& layout,
const LogString& filename)
: maxFileSize(10*1024*1024), maxBackupIndex(1) {
setLayout(layout);
setFile(filename);
Pool pool;
activateOptions(pool);
}
RollingFileAppender::~RollingFileAppender() {
}
void RollingFileAppender::setOption(const LogString& option,
const LogString& value)
{
if (StringHelper::equalsIgnoreCase(option,
LOG4CXX_STR("MAXFILESIZE"), LOG4CXX_STR("maxfilesize"))
|| StringHelper::equalsIgnoreCase(option,
LOG4CXX_STR("MAXIMUMFILESIZE"), LOG4CXX_STR("maximumfilesize")))
{
setMaxFileSize(value);
}
else if (StringHelper::equalsIgnoreCase(option,
LOG4CXX_STR("MAXBACKUPINDEX"), LOG4CXX_STR("maxbackupindex"))
|| StringHelper::equalsIgnoreCase(option,
LOG4CXX_STR("MAXIMUMBACKUPINDEX"), LOG4CXX_STR("maximumbackupindex")))
{
maxBackupIndex = StringHelper::toInt(value);
}
else
{
using namespace log4cxx::rolling;
RollingFileAppenderSkeleton::setOption(option, value);
}
}
int RollingFileAppender::getMaxBackupIndex() const {
return maxBackupIndex;
}
long RollingFileAppender::getMaximumFileSize() const {
return maxFileSize;
}
void RollingFileAppender::setMaxBackupIndex(int maxBackups) {
maxBackupIndex = maxBackups;
}
void RollingFileAppender::setMaximumFileSize(int maxFileSize1) {
maxFileSize = maxFileSize1;
}
void RollingFileAppender::setMaxFileSize(const LogString& value) {
maxFileSize = OptionConverter::toFileSize(value, maxFileSize + 1);
}
void RollingFileAppender::activateOptions(Pool& pool) {
log4cxx::rolling::SizeBasedTriggeringPolicyPtr trigger(
new log4cxx::rolling::SizeBasedTriggeringPolicy());
trigger->setMaxFileSize(maxFileSize);
trigger->activateOptions(pool);
setTriggeringPolicy(trigger);
log4cxx::rolling::FixedWindowRollingPolicyPtr rolling(
new log4cxx::rolling::FixedWindowRollingPolicy());
rolling->setMinIndex(1);
rolling->setMaxIndex(maxBackupIndex);
rolling->setFileNamePattern(getFile() + LOG4CXX_STR(".%i"));
rolling->activateOptions(pool);
setRollingPolicy(rolling);
using namespace log4cxx::rolling;
RollingFileAppenderSkeleton::activateOptions(pool);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/pattern/nameabbreviator.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/helpers/stringhelper.h>
#include <vector>
#include <limits.h>
using namespace log4cxx;
using namespace log4cxx::pattern;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(NameAbbreviator)
NameAbbreviator::NameAbbreviator() {
}
NameAbbreviator::~NameAbbreviator() {
}
namespace log4cxx {
namespace pattern {
/**
* Abbreviator that simply appends full name to buffer.
*/
class NOPAbbreviator : public NameAbbreviator {
public:
DECLARE_ABSTRACT_LOG4CXX_OBJECT(NOPAbbreviator)
BEGIN_LOG4CXX_CAST_MAP()
LOG4CXX_CAST_ENTRY(NOPAbbreviator)
LOG4CXX_CAST_ENTRY_CHAIN(NameAbbreviator)
END_LOG4CXX_CAST_MAP()
/**
* Constructor.
*/
NOPAbbreviator() {
}
/**
* {@inheritDoc}
*/
void abbreviate(LogString::size_type /* nameStart */, LogString& /* buf */) const {
}
};
/**
* Abbreviator that drops starting path elements.
*/
class MaxElementAbbreviator : public NameAbbreviator {
/**
* Maximum number of path elements to output.
*/
const int count;
public:
DECLARE_ABSTRACT_LOG4CXX_OBJECT(MaxElementAbbreviator)
BEGIN_LOG4CXX_CAST_MAP()
LOG4CXX_CAST_ENTRY(MaxElementAbbreviator)
LOG4CXX_CAST_ENTRY_CHAIN(NameAbbreviator)
END_LOG4CXX_CAST_MAP()
/**
* Create new instance.
* @param count maximum number of path elements to output.
*/
MaxElementAbbreviator(const int count1) : count(count1) {
}
/**
* Abbreviate name.
* @param buf buffer to append abbreviation.
* @param nameStart start of name to abbreviate.
*/
void abbreviate(LogString::size_type nameStart, LogString& buf) const {
// We substract 1 from 'len' when assigning to 'end' to avoid out of
// bounds exception in return r.substring(end+1, len). This can happen if
// precision is 1 and the logger name ends with a dot.
LogString::size_type end = buf.length() - 1;
for (LogString::size_type i = count; i > 0; i--) {
end = buf.rfind(0x2E /* '.' */, end - 1);
if ((end == LogString::npos) || (end < nameStart)) {
return;
}
}
buf.erase(buf.begin() + nameStart, buf.begin() + (end + 1));
}
};
/**
* Fragment of an pattern abbreviator.
*
*/
class PatternAbbreviatorFragment {
/**
* Count of initial characters of element to output.
*/
LogString::size_type charCount;
/**
* Character used to represent dropped characters.
* '\0' indicates no representation of dropped characters.
*/
logchar ellipsis;
public:
/**
* Creates a PatternAbbreviatorFragment.
* @param charCount number of initial characters to preserve.
* @param ellipsis character to represent elimination of characters,
* '\0' if no ellipsis is desired.
*/
PatternAbbreviatorFragment(
const int charCount1, const logchar ellipsis1)
: charCount(charCount1), ellipsis(ellipsis1) {
}
PatternAbbreviatorFragment() : charCount(0), ellipsis(0) {
}
PatternAbbreviatorFragment(const PatternAbbreviatorFragment& src)
: charCount(src.charCount), ellipsis(src.ellipsis) {
}
PatternAbbreviatorFragment& operator=(const PatternAbbreviatorFragment& src) {
charCount = src.charCount;
ellipsis = src.ellipsis;
return *this;
}
/**
* 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;
}
};
/**
* Pattern abbreviator.
*
*
*/
class PatternAbbreviator : public NameAbbreviator {
/**
* Element abbreviation patterns.
*/
std::vector<PatternAbbreviatorFragment> fragments;
public:
DECLARE_ABSTRACT_LOG4CXX_OBJECT(PatternAbbreviator)
BEGIN_LOG4CXX_CAST_MAP()
LOG4CXX_CAST_ENTRY(PatternAbbreviator)
LOG4CXX_CAST_ENTRY_CHAIN(NameAbbreviator)
END_LOG4CXX_CAST_MAP()
/**
* Create PatternAbbreviator.
*
* @param fragments element abbreviation patterns.
*/
PatternAbbreviator(const std::vector<PatternAbbreviatorFragment>& fragments1) :
fragments(fragments1) {
if (fragments1.size() == 0) {
throw IllegalArgumentException(LOG4CXX_STR("fragments parameter must contain at least one element"));
}
}
/**
* 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);
}
}
};
}
}
IMPLEMENT_LOG4CXX_OBJECT(NOPAbbreviator)
IMPLEMENT_LOG4CXX_OBJECT(MaxElementAbbreviator)
IMPLEMENT_LOG4CXX_OBJECT(PatternAbbreviator)
NameAbbreviatorPtr NameAbbreviator::getAbbreviator(const LogString& pattern) {
if (pattern.length() > 0) {
// if pattern is just spaces and numbers then
// use MaxElementAbbreviator
LogString trimmed(StringHelper::trim(pattern));
if (trimmed.length() == 0) {
return getDefaultAbbreviator();
}
LogString::size_type i = 0;
while (
(i < trimmed.length()) && (trimmed[i] >= 0x30 /* '0' */)
&& (trimmed[i] <= 0x39 /* '9' */)) {
i++;
}
//
// if all blanks and digits
//
if (i == trimmed.length()) {
return new MaxElementAbbreviator(StringHelper::toInt(trimmed));
}
std::vector<PatternAbbreviatorFragment> fragments;
logchar ellipsis;
int charCount;
LogString::size_type pos = 0;
while (pos < trimmed.length()) {
LogString::size_type ellipsisPos = pos;
if (trimmed[pos] == 0x2A /* '*' */) {
charCount = INT_MAX;
ellipsisPos++;
} else {
if ((trimmed[pos] >= 0x30 /* '0' */)
&& (trimmed[pos] <= 0x39 /* '9' */)) {
charCount = trimmed[pos] - 0x30 /* '0' */;
ellipsisPos++;
} else {
charCount = 0;
}
}
ellipsis = 0;
if (ellipsisPos < trimmed.length()) {
ellipsis = trimmed[ellipsisPos];
if (ellipsis == 0x2E /* '.' */) {
ellipsis = 0;
}
}
fragments.push_back(PatternAbbreviatorFragment(charCount, ellipsis));
pos = trimmed.find(0x2E /* '.' */, pos);
if (pos == LogString::npos) {
break;
}
pos++;
}
NameAbbreviatorPtr abbrev(new PatternAbbreviator(fragments));
return abbrev;
}
//
// no matching abbreviation, return defaultAbbreviator
//
return getDefaultAbbreviator();
}
/**
* Gets default abbreviator.
*
* @return default abbreviator.
*/
NameAbbreviatorPtr NameAbbreviator::getDefaultAbbreviator() {
static NameAbbreviatorPtr def(new NOPAbbreviator());
return def;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/net/syslogappender.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/datagramsocket.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/level.h>
#include <log4cxx/helpers/transcoder.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/private/log4cxx_private.h>
#if LOG4CXX_HAVE_SYSLOG
#include <syslog.h>
#else
/* facility codes */
#define LOG_KERN (0<<3) /* kernel messages */
#define LOG_USER (1<<3) /* random user-level messages */
#define LOG_MAIL (2<<3) /* mail system */
#define LOG_DAEMON (3<<3) /* system daemons */
#define LOG_AUTH (4<<3) /* security/authorization messages */
#define LOG_SYSLOG (5<<3) /* messages generated internally by syslogd */
#define LOG_LPR (6<<3) /* line printer subsystem */
#define LOG_NEWS (7<<3) /* network news subsystem */
#define LOG_UUCP (8<<3) /* UUCP subsystem */
#define LOG_CRON (9<<3) /* clock daemon */
#define LOG_AUTHPRIV (10<<3) /* security/authorization messages (private) */
#define LOG_FTP (11<<3) /* ftp daemon */
/* other codes through 15 reserved for system use */
#define LOG_LOCAL0 (16<<3) /* reserved for local use */
#define LOG_LOCAL1 (17<<3) /* reserved for local use */
#define LOG_LOCAL2 (18<<3) /* reserved for local use */
#define LOG_LOCAL3 (19<<3) /* reserved for local use */
#define LOG_LOCAL4 (20<<3) /* reserved for local use */
#define LOG_LOCAL5 (21<<3) /* reserved for local use */
#define LOG_LOCAL6 (22<<3) /* reserved for local use */
#define LOG_LOCAL7 (23<<3) /* reserved for local use */
#endif
#define LOG_UNDEF -1
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::net;
IMPLEMENT_LOG4CXX_OBJECT(SyslogAppender)
SyslogAppender::SyslogAppender()
: syslogFacility(LOG_USER), facilityPrinting(false), sw(0)
{
this->initSyslogFacilityStr();
}
SyslogAppender::SyslogAppender(const LayoutPtr& layout1,
int syslogFacility1)
: syslogFacility(syslogFacility1), facilityPrinting(false), sw(0)
{
this->layout = layout1;
this->initSyslogFacilityStr();
}
SyslogAppender::SyslogAppender(const LayoutPtr& layout1,
const LogString& syslogHost1, int syslogFacility1)
: syslogFacility(syslogFacility1), facilityPrinting(false), sw(0)
{
this->layout = layout1;
this->initSyslogFacilityStr();
setSyslogHost(syslogHost1);
}
SyslogAppender::~SyslogAppender()
{
finalize();
}
/** Release any resources held by this SyslogAppender.*/
void SyslogAppender::close()
{
closed = true;
if (sw != 0)
{
delete sw;
sw = 0;
}
}
void SyslogAppender::initSyslogFacilityStr()
{
facilityStr = getFacilityString(this->syslogFacility);
if (facilityStr.empty())
{
Pool p;
LogString msg(LOG4CXX_STR("\""));
StringHelper::toString(syslogFacility, p, msg);
msg.append(LOG4CXX_STR("\" is an unknown syslog facility. Defaulting to \"USER\"."));
LogLog::error(msg);
this->syslogFacility = LOG_USER;
facilityStr = LOG4CXX_STR("user:");
}
else
{
facilityStr += LOG4CXX_STR(":");
}
}
/**
Returns the specified syslog facility as a lower-case String,
e.g. "kern", "user", etc.
*/
LogString SyslogAppender::getFacilityString(
int syslogFacility)
{
switch(syslogFacility)
{
case LOG_KERN: return LOG4CXX_STR("kern");
case LOG_USER: return LOG4CXX_STR("user");
case LOG_MAIL: return LOG4CXX_STR("mail");
case LOG_DAEMON: return LOG4CXX_STR("daemon");
case LOG_AUTH: return LOG4CXX_STR("auth");
case LOG_SYSLOG: return LOG4CXX_STR("syslog");
case LOG_LPR: return LOG4CXX_STR("lpr");
case LOG_NEWS: return LOG4CXX_STR("news");
case LOG_UUCP: return LOG4CXX_STR("uucp");
case LOG_CRON: return LOG4CXX_STR("cron");
#ifdef LOG_AUTHPRIV
case LOG_AUTHPRIV: return LOG4CXX_STR("authpriv");
#endif
#ifdef LOG_FTP
case LOG_FTP: return LOG4CXX_STR("ftp");
#endif
case LOG_LOCAL0: return LOG4CXX_STR("local0");
case LOG_LOCAL1: return LOG4CXX_STR("local1");
case LOG_LOCAL2: return LOG4CXX_STR("local2");
case LOG_LOCAL3: return LOG4CXX_STR("local3");
case LOG_LOCAL4: return LOG4CXX_STR("local4");
case LOG_LOCAL5: return LOG4CXX_STR("local5");
case LOG_LOCAL6: return LOG4CXX_STR("local6");
case LOG_LOCAL7: return LOG4CXX_STR("local7");
default: return LogString();
}
}
int SyslogAppender::getFacility(
const LogString& s)
{
if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("KERN"), LOG4CXX_STR("kern")))
{
return LOG_KERN;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("USER"), LOG4CXX_STR("user")))
{
return LOG_USER;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("MAIL"), LOG4CXX_STR("mail")))
{
return LOG_MAIL;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("DAEMON"), LOG4CXX_STR("daemon")))
{
return LOG_DAEMON;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("AUTH"), LOG4CXX_STR("auth")))
{
return LOG_AUTH;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("SYSLOG"), LOG4CXX_STR("syslog")))
{
return LOG_SYSLOG;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LPR"), LOG4CXX_STR("lpr")))
{
return LOG_LPR;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("NEWS"), LOG4CXX_STR("news")))
{
return LOG_NEWS;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("UUCP"), LOG4CXX_STR("uucp")))
{
return LOG_UUCP;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("CRON"), LOG4CXX_STR("cron")))
{
return LOG_CRON;
}
#ifdef LOG_AUTHPRIV
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("AUTHPRIV"), LOG4CXX_STR("authpriv")))
{
return LOG_AUTHPRIV;
}
#endif
#ifdef LOG_FTP
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("FTP"), LOG4CXX_STR("ftp")))
{
return LOG_FTP;
}
#endif
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL0"), LOG4CXX_STR("local0")))
{
return LOG_LOCAL0;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL1"), LOG4CXX_STR("local1")))
{
return LOG_LOCAL1;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL1"), LOG4CXX_STR("local2")))
{
return LOG_LOCAL2;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL1"), LOG4CXX_STR("local3")))
{
return LOG_LOCAL3;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL1"), LOG4CXX_STR("local4")))
{
return LOG_LOCAL4;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL1"), LOG4CXX_STR("local5")))
{
return LOG_LOCAL5;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL1"), LOG4CXX_STR("local6")))
{
return LOG_LOCAL6;
}
else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL1"), LOG4CXX_STR("local7")))
{
return LOG_LOCAL7;
}
else
{
return LOG_UNDEF;
}
}
void SyslogAppender::append(const spi::LoggingEventPtr& event, Pool& p)
{
if (!isAsSevereAsThreshold(event->getLevel()))
return;
LogString msg;
layout->format(msg, event, p);
// On the local host, we can directly use the system function 'syslog'
// if it is available
#if LOG4CXX_HAVE_SYSLOG
if (sw == 0)
{
std::string sbuf;
Transcoder::encode(msg, sbuf);
// use of "%s" to avoid a security hole
::syslog(syslogFacility | event->getLevel()->getSyslogEquivalent(),
"%s", sbuf.c_str());
return;
}
#endif
// We must not attempt to append if sw is null.
if(sw == 0)
{
errorHandler->error(LOG4CXX_STR("No syslog host is set for SyslogAppedender named \"")+
this->name+LOG4CXX_STR("\"."));
return;
}
LogString sbuf(1, 0x3C /* '<' */);
StringHelper::toString((syslogFacility | event->getLevel()->getSyslogEquivalent()), p, sbuf);
sbuf.append(1, (logchar) 0x3E /* '>' */);
if (facilityPrinting)
{
sbuf.append(facilityStr);
}
sbuf.append(msg);
sw->write(sbuf);
}
void SyslogAppender::activateOptions(Pool&)
{
}
void SyslogAppender::setOption(const LogString& option, const LogString& value)
{
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SYSLOGHOST"), LOG4CXX_STR("sysloghost")))
{
setSyslogHost(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("FACILITY"), LOG4CXX_STR("facility")))
{
setFacility(value);
}
else
{
AppenderSkeleton::setOption(option, value);
}
}
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 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();
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logmanager.h>
#include <log4cxx/spi/defaultrepositoryselector.h>
#include <log4cxx/hierarchy.h>
#include <log4cxx/spi/rootlogger.h>
#include <log4cxx/spi/loggerfactory.h>
#include <stdexcept>
#include <log4cxx/level.h>
#include <log4cxx/spi/loggerrepository.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/helpers/loglog.h>
#include <apr_general.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/file.h>
#include <log4cxx/helpers/transcoder.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/helpers/aprinitializer.h>
using namespace log4cxx;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(DefaultRepositorySelector)
void * LogManager::guard = 0;
RepositorySelectorPtr& LogManager::getRepositorySelector() {
//
// call to initialize APR and trigger "start" of logging clock
//
APRInitializer::initialize();
static spi::RepositorySelectorPtr selector;
return selector;
}
void LogManager::setRepositorySelector(spi::RepositorySelectorPtr selector,
void * guard1)
{
if((LogManager::guard != 0) && (LogManager::guard != guard1))
{
throw IllegalArgumentException(LOG4CXX_STR("Attempted to reset the LoggerFactory without possessing the guard."));
}
if(selector == 0)
{
throw IllegalArgumentException(LOG4CXX_STR("RepositorySelector must be non-null."));
}
LogManager::guard = guard1;
LogManager::getRepositorySelector() = selector;
}
LoggerRepositoryPtr& LogManager::getLoggerRepository()
{
if (getRepositorySelector() == 0)
{
LoggerRepositoryPtr hierarchy(new Hierarchy());
RepositorySelectorPtr selector(new DefaultRepositorySelector(hierarchy));
getRepositorySelector() = selector;
}
return getRepositorySelector()->getLoggerRepository();
}
LoggerPtr LogManager::getRootLogger()
{
// Delegate the actual manufacturing of the logger to the logger repository.
return getLoggerRepository()->getRootLogger();
}
/**
Retrieve the appropriate Logger instance.
*/
LoggerPtr LogManager::getLoggerLS(const LogString& name)
{
return getLoggerRepository()->getLogger(name);
}
/**
Retrieve the appropriate Logger instance.
*/
LoggerPtr LogManager::getLoggerLS(const LogString& name,
const spi::LoggerFactoryPtr& factory)
{
// Delegate the actual manufacturing of the logger to the logger repository.
return getLoggerRepository()->getLogger(name, factory);
}
LoggerPtr LogManager::getLogger(const std::string& name) {
LOG4CXX_DECODE_CHAR(n, name);
return getLoggerLS(n);
}
LoggerPtr LogManager::getLogger(const std::string& name,
const spi::LoggerFactoryPtr& factory) {
LOG4CXX_DECODE_CHAR(n, name);
return getLoggerLS(n, factory);
}
LoggerPtr LogManager::exists(const std::string& name)
{
LOG4CXX_DECODE_CHAR(n, name);
return existsLS(n);
}
#if LOG4CXX_WCHAR_T_API
LoggerPtr LogManager::getLogger(const std::wstring& name) {
LOG4CXX_DECODE_WCHAR(n, name);
return getLoggerLS(n);
}
LoggerPtr LogManager::getLogger(const std::wstring& name,
const spi::LoggerFactoryPtr& factory) {
LOG4CXX_DECODE_WCHAR(n, name);
return getLoggerLS(n, factory);
}
LoggerPtr LogManager::exists(const std::wstring& name)
{
LOG4CXX_DECODE_WCHAR(n, name);
return existsLS(n);
}
#endif
#if LOG4CXX_UNICHAR_API
LoggerPtr LogManager::getLogger(const std::basic_string<UniChar>& name) {
LOG4CXX_DECODE_UNICHAR(n, name);
return getLoggerLS(n);
}
LoggerPtr LogManager::getLogger(const std::basic_string<UniChar>& name,
const spi::LoggerFactoryPtr& factory) {
LOG4CXX_DECODE_UNICHAR(n, name);
return getLoggerLS(n, factory);
}
LoggerPtr LogManager::exists(const std::basic_string<UniChar>& name)
{
LOG4CXX_DECODE_UNICHAR(n, name);
return existsLS(n);
}
#endif
#if LOG4CXX_CFSTRING_API
LoggerPtr LogManager::getLogger(const CFStringRef& name) {
LOG4CXX_DECODE_CFSTRING(n, name);
return getLoggerLS(n);
}
LoggerPtr LogManager::getLogger(const CFStringRef& name,
const spi::LoggerFactoryPtr& factory) {
LOG4CXX_DECODE_CFSTRING(n, name);
return getLoggerLS(n, factory);
}
LoggerPtr LogManager::exists(const CFStringRef& name)
{
LOG4CXX_DECODE_CFSTRING(n, name);
return existsLS(n);
}
#endif
LoggerPtr LogManager::existsLS(const LogString& name)
{
return getLoggerRepository()->exists(name);
}
LoggerList LogManager::getCurrentLoggers()
{
return getLoggerRepository()->getCurrentLoggers();
}
void LogManager::shutdown()
{
getLoggerRepository()->shutdown();
}
void LogManager::resetConfiguration()
{
getLoggerRepository()->resetConfiguration();
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/spi/configurator.h>
#include <assert.h>
#include <log4cxx/logger.h>
using namespace log4cxx;
using namespace log4cxx::spi;
IMPLEMENT_LOG4CXX_OBJECT(Configurator)
Configurator::Configurator() {
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/rolling/filerenameaction.h>
using namespace log4cxx;
using namespace log4cxx::rolling;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(FileRenameAction)
FileRenameAction::FileRenameAction(const File& toRename,
const File& renameTo,
bool renameEmptyFile1)
: source(toRename), destination(renameTo), renameEmptyFile(renameEmptyFile1) {
}
bool FileRenameAction::execute(log4cxx::helpers::Pool& pool1) const {
return source.renameTo(destination, pool1);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/stream.h>
#include <log4cxx/helpers/transcoder.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/private/log4cxx_private.h>
using namespace log4cxx;
logstream_base::logstream_ios_base::logstream_ios_base(std::ios_base::fmtflags initval,
int initsize) {
#if LOG4CXX_MEMSET_IOS_BASE
//
// the destructor for std::ios_base in the MSVC STL
// releases a pointer that was not initialized in the constructor.
//
memset(this, 0, sizeof(*this));
#endif
flags(initval);
precision(initsize);
width(initsize);
}
logstream_base::logstream_base(const LoggerPtr& log,
const LevelPtr& lvl) : initset((std::ios_base::fmtflags) -1, 1),
initclear((std::ios_base::fmtflags) 0, 0), fillchar(0), fillset(false), logger(log), level(lvl), location() {
enabled = logger->isEnabledFor(level);
}
logstream_base::~logstream_base() {
}
void logstream_base::insert(std::ios_base& (*manip)(std::ios_base&)) {
get_stream_state(initclear, initset, fillchar, fillset);
(*manip)(initset);
(*manip)(initclear);
refresh_stream_state();
}
bool logstream_base::set_stream_state(std::ios_base& dest, int& dstchar) {
std::ios_base::fmtflags setval = initset.flags();
std::ios_base::fmtflags clrval = initclear.flags();
std::ios_base::fmtflags mask = setval ^ (~clrval);
dest.setf(clrval, mask);
if (initset.precision() == initclear.precision()) {
dest.precision(initset.precision());
}
if (initset.width() == initclear.width()) {
dest.width(initset.width());
}
dstchar = fillchar;
return fillset;
}
logstream_base& logstream_base::endmsg(logstream_base& stream) {
stream.end_message();
return stream;
}
logstream_base& logstream_base::nop(logstream_base& stream) {
return stream;
}
void logstream_base::end_message() {
if (isEnabled()) {
log(logger, level, location);
}
erase();
}
int log4cxx::logstream_base::precision(int p) {
get_stream_state(initclear, initset, fillchar, fillset);
initset.precision(p);
int oldVal = initclear.precision(p);
refresh_stream_state();
return oldVal;
}
int log4cxx::logstream_base::precision() {
get_stream_state(initclear, initset, fillchar, fillset);
return initclear.precision();
}
int log4cxx::logstream_base::width(int w) {
get_stream_state(initclear, initset, fillchar, fillset);
initset.width(w);
int oldVal = initclear.width(w);
refresh_stream_state();
return oldVal;
}
int log4cxx::logstream_base::width() {
get_stream_state(initclear, initset, fillchar, fillset);
return initclear.width();
}
int log4cxx::logstream_base::fill(int newfill) {
get_stream_state(initclear, initset, fillchar, fillset);
int oldfill = fillchar;
fillchar = newfill;
fillset = true;
refresh_stream_state();
return oldfill;
}
int logstream_base::fill() {
get_stream_state(initclear, initset, fillchar, fillset);
return fillchar;
}
std::ios_base::fmtflags logstream_base::flags(std::ios_base::fmtflags newflags) {
get_stream_state(initclear, initset, fillchar, fillset);
initset.flags(newflags);
std::ios_base::fmtflags oldVal = initclear.flags(newflags);
refresh_stream_state();
return oldVal;
}
std::ios_base::fmtflags logstream_base::setf(std::ios_base::fmtflags newflags, std::ios_base::fmtflags mask) {
get_stream_state(initclear, initset, fillchar, fillset);
initset.setf(newflags, mask);
std::ios_base::fmtflags oldVal = initclear.setf(newflags, mask);
refresh_stream_state();
return oldVal;
}
std::ios_base::fmtflags logstream_base::setf(std::ios_base::fmtflags newflags) {
get_stream_state(initclear, initset, fillchar, fillset);
initset.setf(newflags);
std::ios_base::fmtflags oldVal = initclear.setf(newflags);
refresh_stream_state();
return oldVal;
}
void logstream_base::setLevel(const ::log4cxx::LevelPtr& newlevel) {
level = newlevel;
bool oldLevel = enabled;
enabled = logger->isEnabledFor(level);
if (oldLevel != enabled) {
erase();
}
}
bool logstream_base::isEnabledFor(const ::log4cxx::LevelPtr& level) const {
return logger->isEnabledFor(level);
}
void logstream_base::setLocation(const log4cxx::spi::LocationInfo& newlocation) {
if (LOG4CXX_UNLIKELY(enabled)) {
location = newlocation;
}
}
logstream::logstream(const log4cxx::LoggerPtr& logger,
const log4cxx::LevelPtr& level) : logstream_base(logger, level), stream(0) {
}
logstream::logstream(const Ch* loggerName,
const log4cxx::LevelPtr& level)
: logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) {
}
logstream::logstream(const std::basic_string<Ch>& loggerName,
const log4cxx::LevelPtr& level) : logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) {
}
logstream::~logstream() {
delete stream;
}
logstream& logstream::operator<<(logstream_base& (*manip)(logstream_base&)) {
(*manip)(*this);
return *this;
}
logstream& logstream::operator<<(const LevelPtr& level) {
setLevel(level);
return *this;
}
logstream& logstream::operator<<(const log4cxx::spi::LocationInfo& newlocation) {
setLocation(newlocation);
return *this;
}
logstream& logstream::operator>>(const log4cxx::spi::LocationInfo& newlocation) {
setLocation(newlocation);
return *this;
}
logstream& logstream::operator<<(std::ios_base& (*manip)(std::ios_base&)) {
logstream_base::insert(manip);
return *this;
}
logstream::operator std::basic_ostream<char>&() {
if (stream == 0) {
stream = new std::basic_stringstream<Ch>();
refresh_stream_state();
}
return *stream;
}
void logstream::log(LoggerPtr& logger,
const LevelPtr& level,
const log4cxx::spi::LocationInfo& location) {
if (stream != 0) {
std::basic_string<Ch> msg = stream->str();
if (!msg.empty()) {
logger->log(level, msg, location);
}
}
}
void logstream::erase() {
if (stream != 0) {
std::basic_string<Ch> emptyStr;
stream->str(emptyStr);
}
}
void logstream::get_stream_state(std::ios_base& base,
std::ios_base& mask,
int& fill,
bool& fillSet) const {
if (stream != 0) {
std::ios_base::fmtflags flags = stream->flags();
base.flags(flags);
mask.flags(flags);
int width = stream->width();
base.width(width);
mask.width(width);
int precision = stream->precision();
base.precision(precision);
mask.precision(precision);
fill = stream->fill();
fillSet = true;
}
}
void logstream::refresh_stream_state() {
if (stream != 0) {
int fillchar;
if(logstream_base::set_stream_state(*stream, fillchar)) {
stream->fill(fillchar);
}
}
}
#if LOG4CXX_WCHAR_T_API
wlogstream::wlogstream(const log4cxx::LoggerPtr& logger,
const log4cxx::LevelPtr& level) : logstream_base(logger, level), stream(0) {
}
wlogstream::wlogstream(const Ch* loggerName,
const log4cxx::LevelPtr& level)
: logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) {
}
wlogstream::wlogstream(const std::basic_string<Ch>& loggerName,
const log4cxx::LevelPtr& level) : logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) {
}
wlogstream::~wlogstream() {
delete stream;
}
wlogstream& wlogstream::operator<<(logstream_base& (*manip)(logstream_base&)) {
(*manip)(*this);
return *this;
}
wlogstream& wlogstream::operator<<(const LevelPtr& level) {
setLevel(level);
return *this;
}
wlogstream& wlogstream::operator<<(const log4cxx::spi::LocationInfo& newlocation) {
setLocation(newlocation);
return *this;
}
wlogstream& wlogstream::operator>>(const log4cxx::spi::LocationInfo& newlocation) {
setLocation(newlocation);
return *this;
}
wlogstream& wlogstream::operator<<(std::ios_base& (*manip)(std::ios_base&)) {
logstream_base::insert(manip);
return *this;
}
wlogstream::operator std::basic_ostream<wchar_t>&() {
if (stream == 0) {
stream = new std::basic_stringstream<Ch>();
refresh_stream_state();
}
return *stream;
}
void wlogstream::log(LoggerPtr& logger,
const LevelPtr& level,
const log4cxx::spi::LocationInfo& location) {
if (stream != 0) {
std::basic_string<Ch> msg = stream->str();
if (!msg.empty()) {
logger->log(level, msg, location);
}
}
}
void wlogstream::erase() {
if (stream != 0) {
std::basic_string<Ch> emptyStr;
stream->str(emptyStr);
}
}
void wlogstream::get_stream_state(std::ios_base& base,
std::ios_base& mask,
int& fill,
bool& fillSet) const {
if (stream != 0) {
std::ios_base::fmtflags flags = stream->flags();
base.flags(flags);
mask.flags(flags);
int width = stream->width();
base.width(width);
mask.width(width);
int precision = stream->precision();
base.precision(precision);
mask.precision(precision);
fill = stream->fill();
fillSet = true;
}
}
void wlogstream::refresh_stream_state() {
if (stream != 0) {
int fillchar;
if(logstream_base::set_stream_state(*stream, fillchar)) {
stream->fill(fillchar);
}
}
}
#endif
#if LOG4CXX_UNICHAR_API
ulogstream::ulogstream(const Ch* loggerName,
const log4cxx::LevelPtr& level)
: logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) {
}
ulogstream::ulogstream(const std::basic_string<Ch>& loggerName,
const log4cxx::LevelPtr& level) : logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) {
}
#endif
#if LOG4CXX_CFSTRING_API
ulogstream::ulogstream(const CFStringRef& loggerName,
const log4cxx::LevelPtr& level)
: logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) {
}
#endif
#if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API
ulogstream::ulogstream(const log4cxx::LoggerPtr& logger,
const log4cxx::LevelPtr& level) : logstream_base(logger, level), stream(0) {
}
ulogstream::~ulogstream() {
delete stream;
}
ulogstream& ulogstream::operator<<(logstream_base& (*manip)(logstream_base&)) {
(*manip)(*this);
return *this;
}
ulogstream& ulogstream::operator<<(const LevelPtr& level) {
setLevel(level);
return *this;
}
ulogstream& ulogstream::operator<<(const log4cxx::spi::LocationInfo& newlocation) {
setLocation(newlocation);
return *this;
}
ulogstream& ulogstream::operator>>(const log4cxx::spi::LocationInfo& newlocation) {
setLocation(newlocation);
return *this;
}
ulogstream& ulogstream::operator<<(std::ios_base& (*manip)(std::ios_base&)) {
logstream_base::insert(manip);
return *this;
}
ulogstream::operator std::basic_ostream<UniChar>&() {
if (stream == 0) {
stream = new std::basic_stringstream<Ch>();
refresh_stream_state();
}
return *stream;
}
void ulogstream::log(LoggerPtr& logger,
const LevelPtr& level,
const log4cxx::spi::LocationInfo& location) {
if (stream != 0) {
std::basic_string<Ch> msg = stream->str();
if (!msg.empty() && logger->isEnabledFor(level)) {
LOG4CXX_DECODE_UNICHAR(lsmsg, msg);
logger->forcedLogLS(level, lsmsg, location);
}
}
}
void ulogstream::erase() {
if (stream != 0) {
std::basic_string<Ch> emptyStr;
stream->str(emptyStr);
}
}
void ulogstream::get_stream_state(std::ios_base& base,
std::ios_base& mask,
int& fill,
bool& fillSet) const {
if (stream != 0) {
std::ios_base::fmtflags flags = stream->flags();
base.flags(flags);
mask.flags(flags);
int width = stream->width();
base.width(width);
mask.width(width);
int precision = stream->precision();
base.precision(precision);
mask.precision(precision);
fill = stream->fill();
fillSet = true;
}
}
void ulogstream::refresh_stream_state() {
if (stream != 0) {
int fillchar;
if(logstream_base::set_stream_state(*stream, fillchar)) {
stream->fill(fillchar);
}
}
}
#endif
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/socketoutputstream.h>
#include <log4cxx/helpers/socket.h>
#include <log4cxx/helpers/bytebuffer.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(SocketOutputStream)
SocketOutputStream::SocketOutputStream(const SocketPtr& socket1)
: socket(socket1) {
}
SocketOutputStream::~SocketOutputStream() {
}
void SocketOutputStream::close(Pool& p) {
flush(p);
socket->close();
}
void SocketOutputStream::flush(Pool& /* p */) {
if (array.size() > 0) {
ByteBuffer buf((char*) &array[0], array.size());
socket->write(buf);
array.resize(0);
}
}
void SocketOutputStream::write(ByteBuffer& buf, Pool& /* p */ ) {
if (buf.remaining() > 0) {
size_t sz = array.size();
array.resize(sz + buf.remaining());
memcpy(&array[sz], buf.current(), buf.remaining());
buf.position(buf.limit());
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/ndc.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/helpers/threadspecificdata.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
NDC::NDC(const std::string& message)
{
push(message);
}
NDC::~NDC()
{
pop();
}
LogString& NDC::getMessage(NDC::DiagnosticContext& ctx) {
return ctx.first;
}
LogString& NDC::getFullMessage(NDC::DiagnosticContext& ctx) {
return ctx.second;
}
void NDC::clear()
{
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
Stack& stack = data->getStack();
while(!stack.empty()) {
stack.pop();
}
data->recycle();
}
}
NDC::Stack* NDC::cloneStack()
{
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
Stack& stack = data->getStack();
if (!stack.empty()) {
return new Stack(stack);
}
}
return new Stack();
}
void NDC::inherit(NDC::Stack * stack) {
if (stack != NULL) {
ThreadSpecificData::inherit(*stack);
delete stack;
}
}
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;
}
int NDC::getDepth() {
int size = 0;
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
size = data->getStack().size();
if (size == 0) {
data->recycle();
}
}
return size;
}
LogString NDC::pop()
{
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
Stack& stack = data->getStack();
if(!stack.empty())
{
LogString value(getMessage(stack.top()));
stack.pop();
data->recycle();
return value;
}
data->recycle();
}
return LogString();
}
bool NDC::pop(std::string& dst)
{
bool retval = false;
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
Stack& stack = data->getStack();
if(!stack.empty())
{
Transcoder::encode(getMessage(stack.top()), dst);
stack.pop();
retval = true;
}
data->recycle();
}
return retval;
}
LogString NDC::peek()
{
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
Stack& stack = data->getStack();
if(!stack.empty())
{
return getMessage(stack.top());
}
data->recycle();
}
return LogString();
}
bool NDC::peek(std::string& dst)
{
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
Stack& stack = data->getStack();
if(!stack.empty())
{
Transcoder::encode(getMessage(stack.top()), dst);
return true;
}
data->recycle();
}
return false;
}
void NDC::pushLS(const LogString& message)
{
ThreadSpecificData::push(message);
}
void NDC::push(const std::string& message)
{
LOG4CXX_DECODE_CHAR(msg, message);
pushLS(msg);
}
void NDC::remove()
{
clear();
}
bool NDC::empty() {
bool empty = true;
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
Stack& stack = data->getStack();
empty = stack.empty();
if (empty) {
data->recycle();
}
}
return empty;
}
#if LOG4CXX_WCHAR_T_API
NDC::NDC(const std::wstring& message)
{
push(message);
}
void NDC::push(const std::wstring& message)
{
LOG4CXX_DECODE_WCHAR(msg, message);
pushLS(msg);
}
bool NDC::pop(std::wstring& dst)
{
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
Stack& stack = data->getStack();
if(!stack.empty())
{
Transcoder::encode(getMessage(stack.top()), dst);
stack.pop();
data->recycle();
return true;
}
data->recycle();
}
return false;
}
bool NDC::peek(std::wstring& dst)
{
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
Stack& stack = data->getStack();
if(!stack.empty())
{
Transcoder::encode(getMessage(stack.top()), dst);
return true;
}
data->recycle();
}
return false;
}
#endif
#if LOG4CXX_UNICHAR_API
NDC::NDC(const std::basic_string<UniChar>& message)
{
push(message);
}
void NDC::push(const std::basic_string<UniChar>& message)
{
LOG4CXX_DECODE_UNICHAR(msg, message);
pushLS(msg);
}
bool NDC::pop(std::basic_string<UniChar>& dst)
{
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
Stack& stack = data->getStack();
if(!stack.empty())
{
Transcoder::encode(stack.top().message, dst);
stack.pop();
data->recycle();
return true;
}
data->recycle();
}
return false;
}
bool NDC::peek(std::basic_string<UniChar>& dst)
{
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
Stack& stack = data->getStack();
if(!stack.empty())
{
Transcoder::encode(stack.top().message, dst);
return true;
}
data->recycle();
}
return false;
}
#endif
#if LOG4CXX_CFSTRING_API
NDC::NDC(const CFStringRef& message)
{
push(message);
}
void NDC::push(const CFStringRef& message)
{
LOG4CXX_DECODE_CFSTRING(msg, message);
pushLS(msg);
}
bool NDC::pop(CFStringRef& dst)
{
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
Stack& stack = data->getStack();
if(!stack.empty())
{
dst = Transcoder::encode(stack.top().message);
stack.pop();
data->recycle();
return true;
}
data->recycle();
}
return false;
}
bool NDC::peek(CFStringRef& dst)
{
ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
if (data != 0) {
Stack& stack = data->getStack();
if(!stack.empty())
{
dst = Transcoder::encode(stack.top().message);
return true;
}
data->recycle();
}
return false;
}
#endif
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/bytebuffer.h>
#include <log4cxx/helpers/exception.h>
#include <apr_pools.h>
#include <log4cxx/helpers/pool.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
ByteBuffer::ByteBuffer(char* data1, size_t capacity)
: base(data1), pos(0), lim(capacity), cap(capacity) {
}
ByteBuffer::~ByteBuffer() {
}
void ByteBuffer::clear() {
lim = cap;
pos = 0;
}
void ByteBuffer::flip() {
lim = pos;
pos = 0;
}
void ByteBuffer::position(size_t newPosition) {
if (newPosition < lim) {
pos = newPosition;
} else {
pos = lim;
}
}
void ByteBuffer::limit(size_t newLimit) {
if (newLimit > cap) {
throw IllegalArgumentException(LOG4CXX_STR("newLimit"));
}
lim = newLimit;
}
bool ByteBuffer::put(char byte) {
if (pos < lim) {
base[pos++] = byte;
return true;
}
return false;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/bufferedwriter.h>
#include <log4cxx/helpers/pool.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(BufferedWriter)
BufferedWriter::BufferedWriter(WriterPtr& out1)
: out(out1), sz(1024) {
}
BufferedWriter::BufferedWriter(WriterPtr& out1, size_t sz1)
: out(out1), sz(sz1) {
}
BufferedWriter::~BufferedWriter() {
}
void BufferedWriter::close(Pool& p) {
flush(p);
out->close(p);
}
void BufferedWriter::flush(Pool& p) {
if (buf.length() > 0) {
out->write(buf, p);
buf.erase(buf.begin(), buf.end());
}
}
void BufferedWriter::write(const LogString& str, Pool& p) {
if (buf.length() + str.length() > sz) {
out->write(buf, p);
buf.erase(buf.begin(), buf.end());
}
if (str.length() > sz) {
out->write(str, p);
} else {
buf.append(str);
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/simplelayout.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/level.h>
using namespace log4cxx;
using namespace log4cxx::spi;
IMPLEMENT_LOG4CXX_OBJECT(SimpleLayout)
void SimpleLayout::format(LogString& output,
const spi::LoggingEventPtr& event,
log4cxx::helpers::Pool&) const
{
output.append(event->getLevel()->toString());
output.append(LOG4CXX_STR(" - "));
output.append(event->getRenderedMessage());
output.append(LOG4CXX_EOL);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/pattern/filelocationpatternconverter.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/spi/location/locationinfo.h>
using namespace log4cxx;
using namespace log4cxx::pattern;
using namespace log4cxx::spi;
using namespace helpers;
IMPLEMENT_LOG4CXX_OBJECT(FileLocationPatternConverter)
FileLocationPatternConverter::FileLocationPatternConverter() :
LoggingEventPatternConverter(LOG4CXX_STR("File Location"),
LOG4CXX_STR("file")) {
}
PatternConverterPtr FileLocationPatternConverter::newInstance(
const std::vector<LogString>& /* options */ ) {
static PatternConverterPtr instance(new FileLocationPatternConverter());
return instance;
}
void FileLocationPatternConverter::format(
const LoggingEventPtr& event,
LogString& toAppendTo,
Pool& /* p */ ) const {
append(toAppendTo, event->getLocationInformation().getFileName());
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/spi/rootlogger.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/level.h>
#include <log4cxx/appender.h>
using namespace log4cxx;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
RootLogger::RootLogger(Pool& pool, const LevelPtr& level1) :
Logger(pool, LOG4CXX_STR("root"))
{
setLevel(level1);
}
const LevelPtr& RootLogger::getEffectiveLevel() const
{
return level;
}
void RootLogger::setLevel(const LevelPtr& level1)
{
if(level1 == 0)
{
LogLog::error(LOG4CXX_STR("You have tried to set a null level to root."));
}
else
{
this->level = level1;
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/outputstreamwriter.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/helpers/charsetencoder.h>
#include <log4cxx/helpers/bytebuffer.h>
#include <log4cxx/helpers/stringhelper.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(OutputStreamWriter)
OutputStreamWriter::OutputStreamWriter(OutputStreamPtr& out1)
: out(out1), enc(CharsetEncoder::getDefaultEncoder()) {
if (out1 == 0) {
throw NullPointerException(LOG4CXX_STR("out parameter may not be null."));
}
}
OutputStreamWriter::OutputStreamWriter(OutputStreamPtr& out1,
CharsetEncoderPtr &enc1)
: out(out1), enc(enc1) {
if (out1 == 0) {
throw NullPointerException(LOG4CXX_STR("out parameter may not be null."));
}
if (enc1 == 0) {
throw NullPointerException(LOG4CXX_STR("enc parameter may not be null."));
}
}
OutputStreamWriter::~OutputStreamWriter() {
}
void OutputStreamWriter::close(Pool& p) {
out->close(p);
}
void OutputStreamWriter::flush(Pool& p) {
out->flush(p);
}
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);
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/inputstream.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(InputStream)
InputStream::InputStream() {
}
InputStream::~InputStream() {
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/system.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/helpers/pool.h>
#include <apr_file_io.h>
#include <apr_user.h>
#include <apr_env.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
LogString System::getProperty(const LogString& lkey)
{
if (lkey.empty())
{
throw IllegalArgumentException(LOG4CXX_STR("key is empty"));
}
LogString rv;
if (lkey == LOG4CXX_STR("java.io.tmpdir")) {
Pool p;
const char* dir = NULL;
apr_status_t stat = apr_temp_dir_get(&dir, p.getAPRPool());
if (stat == APR_SUCCESS) {
Transcoder::decode(dir, rv);
}
return rv;
}
if (lkey == LOG4CXX_STR("user.dir")) {
Pool p;
char* dir = NULL;
apr_status_t stat = apr_filepath_get(&dir, APR_FILEPATH_NATIVE,
p.getAPRPool());
if (stat == APR_SUCCESS) {
Transcoder::decode(dir, rv);
}
return rv;
}
#if APR_HAS_USER
if (lkey == LOG4CXX_STR("user.home") || lkey == LOG4CXX_STR("user.name")) {
Pool pool;
apr_uid_t userid;
apr_gid_t groupid;
apr_pool_t* p = pool.getAPRPool();
apr_status_t stat = apr_uid_current(&userid, &groupid, p);
if (stat == APR_SUCCESS) {
char* username = NULL;
stat = apr_uid_name_get(&username, userid, p);
if (stat == APR_SUCCESS) {
if (lkey == LOG4CXX_STR("user.name")) {
Transcoder::decode(username, rv);
} else {
char* dirname = NULL;
stat = apr_uid_homepath_get(&dirname, username, p);
if (stat == APR_SUCCESS) {
Transcoder::decode(dirname, rv);
}
}
}
}
return rv;
}
#endif
LOG4CXX_ENCODE_CHAR(key, lkey);
Pool p;
char* value = NULL;
apr_status_t stat = apr_env_get(&value, key.c_str(),
p.getAPRPool());
if (stat == APR_SUCCESS) {
Transcoder::decode((const char*) value, rv);
}
return rv;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/rolling/rollingpolicy.h>
using namespace log4cxx::rolling;
IMPLEMENT_LOG4CXX_OBJECT(RollingPolicy)
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/pattern/loggerpatternconverter.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/spi/location/locationinfo.h>
using namespace log4cxx;
using namespace log4cxx::pattern;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(LoggerPatternConverter)
LoggerPatternConverter::LoggerPatternConverter(
const std::vector<LogString>& options) :
NamePatternConverter(LOG4CXX_STR("Logger"),
LOG4CXX_STR("logger"), options) {
}
PatternConverterPtr LoggerPatternConverter::newInstance(
const std::vector<LogString>& options) {
if (options.size() == 0) {
static PatternConverterPtr def(new LoggerPatternConverter(options));
return def;
}
return new LoggerPatternConverter(options);
}
void LoggerPatternConverter::format(
const LoggingEventPtr& event,
LogString& toAppendTo,
Pool& /* p */ ) const {
int initialLength = toAppendTo.length();
toAppendTo.append(event->getLoggerName());
abbreviate(initialLength, toAppendTo);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/thread.h>
#include <log4cxx/helpers/exception.h>
#include <apr_thread_proc.h>
#include <apr_atomic.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/helpers/threadlocal.h>
using namespace log4cxx::helpers;
using namespace log4cxx;
Thread::Thread() : thread(NULL), alive(0), interruptedStatus(0) {
}
Thread::~Thread() {
join();
}
Thread::LaunchPackage::LaunchPackage(Thread* t, Runnable r, void* d) : thread(t), runnable(r), data(d) {
}
Thread* Thread::LaunchPackage::getThread() const {
return thread;
}
Runnable Thread::LaunchPackage::getRunnable() const {
return runnable;
}
void* Thread::LaunchPackage::getData() const {
return data;
}
void* Thread::LaunchPackage::operator new(size_t sz, Pool& p) {
return p.palloc(sz);
}
void Thread::LaunchPackage::operator delete(void* mem, Pool& p) {
}
void Thread::run(Runnable start, void* data) {
#if APR_HAS_THREADS
//
// if attempting a second run method on the same Thread object
// throw an exception
//
if (thread != NULL) {
throw IllegalStateException();
}
apr_threadattr_t* attrs;
apr_status_t stat = apr_threadattr_create(&attrs, p.getAPRPool());
if (stat != APR_SUCCESS) {
throw ThreadException(stat);
}
// create LaunchPackage on the thread's memory pool
LaunchPackage* package = new(p) LaunchPackage(this, start, data);
stat = apr_thread_create(&thread, attrs,
launcher, package, p.getAPRPool());
if (stat != APR_SUCCESS) {
throw ThreadException(stat);
}
#else
throw ThreadException(LOG4CXX_STR("APR_HAS_THREADS is not true"));
#endif
}
Thread::LaunchStatus::LaunchStatus(volatile unsigned int* p) : alive(p) {
apr_atomic_set32(alive, 0xFFFFFFFF);
}
Thread::LaunchStatus::~LaunchStatus() {
apr_atomic_set32(alive, 0);
}
#if APR_HAS_THREADS
void* LOG4CXX_THREAD_FUNC Thread::launcher(apr_thread_t* thread, void* data) {
LaunchPackage* package = (LaunchPackage*) data;
ThreadLocal& tls = getThreadLocal();
tls.set(package->getThread());
LaunchStatus alive(&package->getThread()->alive);
void* retval = (package->getRunnable())(thread, package->getData());
apr_thread_exit(thread, 0);
return retval;
}
#endif
void Thread::join() {
#if APR_HAS_THREADS
if (thread != NULL) {
apr_status_t startStat;
apr_status_t stat = apr_thread_join(&startStat, thread);
thread = NULL;
if (stat != APR_SUCCESS) {
throw ThreadException(stat);
}
}
#endif
}
ThreadLocal& Thread::getThreadLocal() {
static ThreadLocal tls;
return tls;
}
void Thread::currentThreadInterrupt() {
#if APR_HAS_THREADS
void* tls = getThreadLocal().get();
if (tls != 0) {
((Thread*) tls)->interrupt();
}
#endif
}
void Thread::interrupt() {
apr_atomic_set32(&interruptedStatus, 0xFFFFFFFF);
}
bool Thread::interrupted() {
#if APR_HAS_THREADS
void* tls = getThreadLocal().get();
if (tls != 0) {
return apr_atomic_xchg32(&(((Thread*) tls)->interruptedStatus), 0) != 0;
}
#endif
return false;
}
bool Thread::isCurrentThread() const {
#if APR_HAS_THREADS
const void* tls = getThreadLocal().get();
return (tls == this);
#else
return true;
#endif
}
bool Thread::isAlive() {
return apr_atomic_read32(&alive) != 0;
}
void Thread::ending() {
apr_atomic_set32(&alive, 0);
}
void Thread::sleep(int duration) {
#if APR_HAS_THREADS
if(interrupted()) {
throw InterruptedException();
}
#endif
if (duration > 0) {
apr_sleep(duration*1000);
}
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/systemerrwriter.h>
#include <log4cxx/helpers/transcoder.h>
#include <stdio.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/private/log4cxx_private.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(SystemErrWriter)
SystemErrWriter::SystemErrWriter() {
}
SystemErrWriter::~SystemErrWriter() {
}
void SystemErrWriter::close(Pool& /* p */) {
}
void SystemErrWriter::flush(Pool& /* p */) {
flush();
}
void SystemErrWriter::write(const LogString& str, Pool& /* p */) {
write(str);
}
bool SystemErrWriter::isWide() {
#if LOG4CXX_FORCE_WIDE_CONSOLE
return true;
#elif LOG4CXX_FORCE_BYTE_CONSOLE || !LOG4CXX_HAS_FWIDE
return false;
#else
return fwide(stderr, 0) > 0;
#endif
}
void SystemErrWriter::write(const LogString& str) {
#if LOG4CXX_WCHAR_T_API
if (isWide()) {
LOG4CXX_ENCODE_WCHAR(msg, str);
fputws(msg.c_str(), stderr);
return;
}
#endif
LOG4CXX_ENCODE_CHAR(msg, str);
fputs(msg.c_str(), stderr);
}
void SystemErrWriter::flush() {
fflush(stderr);
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define __STDC_CONSTANT_MACROS
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/transcoder.h>
#include <algorithm>
#include <vector>
#include <apr_strings.h>
#include <log4cxx/helpers/pool.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/private/log4cxx_private.h>
#include <cctype>
#include <apr.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
bool StringHelper::equalsIgnoreCase(const LogString& s1, const logchar* upper, const logchar* lower) {
for (LogString::const_iterator iter = s1.begin();
iter != s1.end();
iter++, upper++, lower++) {
if (*iter != *upper && *iter != * lower) return false;
}
return (*upper == 0);
}
bool StringHelper::equalsIgnoreCase(const LogString& s1, const LogString& upper, const LogString& lower) {
LogString::const_iterator u = upper.begin();
LogString::const_iterator l = lower.begin();
LogString::const_iterator iter = s1.begin();
for (;
iter != s1.end() && u != upper.end() && l != lower.end();
iter++, u++, l++) {
if (*iter != *u && *iter != *l) return false;
}
return u == upper.end() && iter == s1.end();
}
LogString StringHelper::toLowerCase(const LogString& s)
{
LogString d;
std::transform(s.begin(), s.end(),
std::insert_iterator<LogString>(d, d.begin()), tolower);
return d;
}
LogString StringHelper::trim(const LogString& s)
{
LogString::size_type pos = s.find_first_not_of(' ');
if (pos == std::string::npos)
{
return LogString();
}
LogString::size_type n = s.find_last_not_of(' ') - pos + 1;
return s.substr(pos, n);
}
bool StringHelper::startsWith(const LogString& s, const LogString& prefix)
{
return s.compare(0, prefix.length(), prefix) == 0;
}
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;
}
int StringHelper::toInt(const LogString& s) {
std::string as;
Transcoder::encode(s, as);
return atoi(as.c_str());
}
log4cxx_int64_t StringHelper::toInt64(const LogString& s) {
std::string as;
Transcoder::encode(s, as);
return apr_atoi64(as.c_str());
}
void StringHelper::toString(int n, Pool& pool, LogString& s) {
char* fmt = pool.itoa(n);
Transcoder::decode(fmt, s);
}
void StringHelper::toString(bool val, LogString& dst) {
if (val) {
dst.append(LOG4CXX_STR("true"));
} else {
dst.append(LOG4CXX_STR("false"));
}
}
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 StringHelper::toString(size_t n, Pool& pool, LogString& s) {
toString((log4cxx_int64_t) n, pool, s);
}
LogString StringHelper::format(const LogString& pattern, const std::vector<LogString>& params) {
LogString result;
int i = 0;
while(pattern[i] != 0) {
if (pattern[i] == 0x7B /* '{' */ && pattern[i + 1] >= 0x30 /* '0' */ &&
pattern[i + 1] <= 0x39 /* '9' */ && pattern[i + 2] == 0x7D /* '}' */) {
int arg = pattern[i + 1] - 0x30 /* '0' */;
result = result + params[arg];
i += 3;
} else {
result = result + pattern[i];
i++;
}
}
return result;
}
| C++ |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/strftimedateformat.h>
#include <apr_time.h>
#include <log4cxx/helpers/transcoder.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
StrftimeDateFormat::StrftimeDateFormat(const LogString& fmt)
: timeZone(TimeZone::getDefault()) {
log4cxx::helpers::Transcoder::encode(fmt, pattern);
}
StrftimeDateFormat::~StrftimeDateFormat() {
}
void StrftimeDateFormat::format(LogString& s, log4cxx_time_t time, Pool& /* p */ ) const {
apr_time_exp_t exploded;
apr_status_t stat = timeZone->explode(&exploded, time);
if (stat == APR_SUCCESS) {
const apr_size_t bufSize = 255;
char buf[bufSize];
apr_size_t bufLen;
stat = apr_strftime(buf, &bufLen, bufSize, pattern.c_str(), &exploded);
if (stat == APR_SUCCESS) {
log4cxx::helpers::Transcoder::decode(std::string(buf, bufLen), s);
}
}
}
void StrftimeDateFormat::setTimeZone(const TimeZonePtr& zone) {
timeZone = zone;
}
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.