Update of /cvsroot/objecthandler/log4cxx-0.9.7/tests/src
In directory sc8-pr-cvs3.sourceforge.net:/tmp/cvs-serv25784/tests/src
Added Files:
Makefile.am asyncappendertestcase.cpp drfatestcase.cpp
hierarchythresholdtestcase.cpp l7dtestcase.cpp
loggertestcase.cpp main.cpp minimumtestcase.cpp
patternlayouttest.cpp shortsocketserver.cpp vectorappender.cpp
vectorappender.h
Log Message:
--- NEW FILE: main.cpp ---
/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed 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 <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include <stdexcept>
#include <iostream>
int main( int argc, char **argv)
{
CppUnit::TextUi::TestRunner runner;
CppUnit::TestFactoryRegistry ®istry =
CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest(registry.makeTest());
bool wasSuccessful = true;
if (argc > 1)
{
for (int n = 1; n < argc; n++)
{
try
{
wasSuccessful = runner.run(argv[n], false) && wasSuccessful;
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
}
else
{
bool wasSuccessful = runner.run("", false);
}
return wasSuccessful ? EXIT_SUCCESS : EXIT_FAILURE;
}
--- NEW FILE: patternlayouttest.cpp ---
/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed 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 <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <log4cxx/logger.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/mdc.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/fileappender.h>
#include "util/compare.h"
#include "util/transformer.h"
#include "util/absolutedateandtimefilter.h"
#include "util/iso8601filter.h"
#include "util/absolutetimefilter.h"
#include "util/relativetimefilter.h"
#include "util/controlfilter.h"
#include "util/threadfilter.h"
#include "util/linenumberfilter.h"
#define FILTERED _T("output/filtered")
#define TEMP _T("output/temp")
#define PAT0 _T("\\[\\d*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message \\d{1,2}")
#define PAT1 ISO8601_PAT _T(" ") PAT0
#define PAT2 ABSOLUTE_DATE_AND_TIME_PAT _T(" ") PAT0
#define PAT3 ABSOLUTE_TIME_PAT _T(" ") PAT0
#define PAT4 RELATIVE_TIME_PAT _T(" ") PAT0
#define PAT5 _T("\\[\\d*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* : Message \\d{1,2}")
#define PAT6 _T("\\[\\d*]\\ (DEBUG|INFO |WARN |ERROR|FATAL) .*patternlayouttest.cpp\\(\\d{1,4}\\): Message \\d{1,3}")
#define PAT11a _T("^(DEBUG|INFO |WARN |ERROR|FATAL) \\[\\d*]\\ log4j.PatternLayoutTest: Message \\d{1,2}")
#define PAT11b _T("^(DEBUG|INFO |WARN |ERROR|FATAL) \\[\\d*]\\ root: Message \\d{1,2}")
#define PAT12 _T("^\\[\\d*]\\ (DEBUG|INFO |WARN |ERROR|FATAL) ")\
_T(".*patternlayouttest.cpp\\(\\d{1,4}\\): ")\
_T("Message \\d{1,2}")
#define PAT_MDC_1 _T("")
using namespace log4cxx;
class PatternLayoutTest : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(PatternLayoutTest);
CPPUNIT_TEST(test1);
CPPUNIT_TEST(test2);
CPPUNIT_TEST(test3);
CPPUNIT_TEST(test4);
CPPUNIT_TEST(test5);
CPPUNIT_TEST(test6);
CPPUNIT_TEST(test7);
CPPUNIT_TEST(test8);
CPPUNIT_TEST(test9);
CPPUNIT_TEST(test10);
CPPUNIT_TEST(test11);
CPPUNIT_TEST(test12);
CPPUNIT_TEST(testMDC1);
CPPUNIT_TEST(testMDC2);
CPPUNIT_TEST_SUITE_END();
LoggerPtr root;
LoggerPtr logger;
public:
void setUp()
{
root = Logger::getRootLogger();
logger = Logger::getLogger(_T("java.org.apache.log4j.PatternLayoutTest"));
}
void tearDown()
{
root->getLoggerRepository()->resetConfiguration();
}
void test1()
{
PropertyConfigurator::configure(_T("input/patternLayout1.properties"));
common();
CPPUNIT_ASSERT(Compare::compare(TEMP, _T("witness/patternLayout.1")));
}
void test2()
{
PropertyConfigurator::configure(_T("input/patternLayout2.properties"));
common();
ControlFilter filter1;
filter1 << PAT1;
ISO8601Filter filter2;
ThreadFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
tcout << _T("UnexpectedFormatException :") << e.getMessage() << std::endl;
throw;
}
CPPUNIT_ASSERT(Compare::compare(FILTERED, _T("witness/patternLayout.2")));
}
void test3()
{
PropertyConfigurator::configure(_T("input/patternLayout3.properties"));
common();
ControlFilter filter1;
filter1 << PAT1;
ISO8601Filter filter2;
ThreadFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
tcout << _T("UnexpectedFormatException :") << e.getMessage() << std::endl;
throw;
}
CPPUNIT_ASSERT(Compare::compare(FILTERED, _T("witness/patternLayout.3")));
}
// Output format:
// 06 avr. 2002 18:30:58,937 [12345] DEBUG atternLayoutTest - Message 0
void test4()
{
PropertyConfigurator::configure(_T("input/patternLayout4.properties"));
common();
ControlFilter filter1;
filter1 << PAT2;
AbsoluteDateAndTimeFilter filter2;
ThreadFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
tcout << _T("UnexpectedFormatException :") << e.getMessage() << std::endl;
throw;
}
CPPUNIT_ASSERT(Compare::compare(FILTERED, _T("witness/patternLayout.4")));
}
void test5()
{
PropertyConfigurator::configure(_T("input/patternLayout5.properties"));
common();
ControlFilter filter1;
filter1 << PAT2;
AbsoluteDateAndTimeFilter filter2;
ThreadFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
tcout << _T("UnexpectedFormatException :") << e.getMessage() << std::endl;
throw;
}
CPPUNIT_ASSERT(Compare::compare(FILTERED, _T("witness/patternLayout.5")));
}
void test6()
{
PropertyConfigurator::configure(_T("input/patternLayout6.properties"));
common();
ControlFilter filter1;
filter1 << PAT3;
AbsoluteTimeFilter filter2;
ThreadFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
tcout << _T("UnexpectedFormatException :") << e.getMessage() << std::endl;
throw;
}
CPPUNIT_ASSERT(Compare::compare(FILTERED, _T("witness/patternLayout.6")));
}
void test7()
{
PropertyConfigurator::configure(_T("input/patternLayout7.properties"));
common();
ControlFilter filter1;
filter1 << PAT3;
AbsoluteTimeFilter filter2;
ThreadFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
tcout << _T("UnexpectedFormatException :") << e.getMessage() << std::endl;
throw;
}
CPPUNIT_ASSERT(Compare::compare(FILTERED, _T("witness/patternLayout.7")));
}
void test8()
{
PropertyConfigurator::configure(_T("input/patternLayout8.properties"));
common();
ControlFilter filter1;
filter1 << PAT4;
RelativeTimeFilter filter2;
ThreadFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
tcout << _T("UnexpectedFormatException :") << e.getMessage() << std::endl;
throw;
}
CPPUNIT_ASSERT(Compare::compare(FILTERED, _T("witness/patternLayout.8")));
}
void test9()
{
PropertyConfigurator::configure(_T("input/patternLayout9.properties"));
common();
ControlFilter filter1;
filter1 << PAT5;
ThreadFilter filter2;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
tcout << _T("UnexpectedFormatException :") << e.getMessage() << std::endl;
throw;
}
CPPUNIT_ASSERT(Compare::compare(FILTERED, _T("witness/patternLayout.9")));
}
void test10()
{
PropertyConfigurator::configure(_T("input/patternLayout10.properties"));
common();
ControlFilter filter1;
filter1 << PAT6;
ThreadFilter filter2;
LineNumberFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
tcout << _T("UnexpectedFormatException :") << e.getMessage() << std::endl;
throw;
}
CPPUNIT_ASSERT(Compare::compare(FILTERED, _T("witness/patternLayout.10")));
}
void test11()
{
PropertyConfigurator::configure(_T("input/patternLayout11.properties"));
common();
ControlFilter filter1;
filter1 << PAT11a << PAT11b;
ThreadFilter filter2;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
tcout << _T("UnexpectedFormatException :") << e.getMessage() << std::endl;
throw;
}
CPPUNIT_ASSERT(Compare::compare(FILTERED, _T("witness/patternLayout.11")));
}
void test12()
{
PropertyConfigurator::configure(_T("input/patternLayout12.properties"));
common();
ControlFilter filter1;
filter1 << PAT12;
ThreadFilter filter2;
LineNumberFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
try
{
Transformer::transform(TEMP, FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
tcout << _T("UnexpectedFormatException :") << e.getMessage() << std::endl;
throw;
}
CPPUNIT_ASSERT(Compare::compare(FILTERED, _T("witness/patternLayout.12")));
}
void testMDC1()
{
PropertyConfigurator::configure(_T("input/patternLayout.mdc.1.properties"));
MDC::put(_T("key1"), _T("va11"));
MDC::put(_T("key2"), _T("va12"));
logger->debug(_T("Hello World"));
MDC::clear();
CPPUNIT_ASSERT(Compare::compare(TEMP, _T("witness/patternLayout.mdc.1")));
}
void testMDC2()
{
String OUTPUT_FILE = _T("output/patternLayout.mdc.2");
String WITNESS_FILE = _T("witness/patternLayout.mdc.2");
String mdcMsgPattern1 = _T("%m : %X%n");
String mdcMsgPattern2 = _T("%m : %X{key1}%n");
String mdcMsgPattern3 = _T("%m : %X{key2}%n");
String mdcMsgPattern4 = _T("%m : %X{key3}%n");
String mdcMsgPattern5 = _T("%m : %X{key1},%X{key2},%X{key3}%n");
// set up appender
PatternLayoutPtr layout = new PatternLayout(_T("%m%n"));
AppenderPtr appender = new FileAppender(layout, OUTPUT_FILE, false);
// set appender on root and set level to debug
root->addAppender(appender);
root->setLevel(Level::DEBUG);
// output starting message
root->debug(_T("starting mdc pattern test"));
layout->setConversionPattern(mdcMsgPattern1);
layout->activateOptions();
root->debug(_T("empty mdc, no key specified in pattern"));
layout->setConversionPattern(mdcMsgPattern2);
layout->activateOptions();
root->debug(_T("empty mdc, key1 in pattern"));
layout->setConversionPattern(mdcMsgPattern3);
layout->activateOptions();
root->debug(_T("empty mdc, key2 in pattern"));
layout->setConversionPattern(mdcMsgPattern4);
layout->activateOptions();
root->debug(_T("empty mdc, key3 in pattern"));
layout->setConversionPattern(mdcMsgPattern5);
layout->activateOptions();
root->debug(_T("empty mdc, key1, key2, and key3 in pattern"));
MDC::put(_T("key1"), _T("value1"));
MDC::put(_T("key2"), _T("value2"));
layout->setConversionPattern(mdcMsgPattern1);
layout->activateOptions();
root->debug(_T("filled mdc, no key specified in pattern"));
layout->setConversionPattern(mdcMsgPattern2);
layout->activateOptions();
root->debug(_T("filled mdc, key1 in pattern"));
layout->setConversionPattern(mdcMsgPattern3);
layout->activateOptions();
root->debug(_T("filled mdc, key2 in pattern"));
layout->setConversionPattern(mdcMsgPattern4);
layout->activateOptions();
root->debug(_T("filled mdc, key3 in pattern"));
layout->setConversionPattern(mdcMsgPattern5);
layout->activateOptions();
root->debug(_T("filled mdc, key1, key2, and key3 in pattern"));
MDC::remove(_T("key1"));
MDC::remove(_T("key2"));
layout->setConversionPattern(_T("%m%n"));
layout->activateOptions();
root->debug(_T("finished mdc pattern test"));
CPPUNIT_ASSERT(Compare::compare(OUTPUT_FILE, WITNESS_FILE));
}
void common()
{
int i = -1;
LOG4CXX_DEBUG(logger, _T("Message ") << ++i);
LOG4CXX_DEBUG(root, _T("Message ") << i);
LOG4CXX_INFO(logger, _T("Message ") << ++i);
LOG4CXX_INFO(root, _T("Message ") << i);
LOG4CXX_WARN(logger, _T("Message ") << ++i);
LOG4CXX_WARN(root, _T("Message ") << i);
LOG4CXX_ERROR(logger, _T("Message ") << ++i);
LOG4CXX_ERROR(root, _T("Message ") << i);
LOG4CXX_FATAL(logger, _T("Message ") << ++i);
LOG4CXX_FATAL(root, _T("Message ") << i);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(PatternLayoutTest);
--- NEW FILE: asyncappendertestcase.cpp ---
/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed 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 <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <log4cxx/logger.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/simplelayout.h>
#include "vectorappender.h"
#include <log4cxx/asyncappender.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
/**
A superficial but general test of log4j.
*/
class AsyncAppenderTestCase : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(AsyncAppenderTestCase);
CPPUNIT_TEST(closeTest);
CPPUNIT_TEST(test2);
CPPUNIT_TEST(test3);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {}
void tearDown()
{
LogManager::shutdown();
}
// this test checks whether it is possible to write to a closed AsyncAppender
void closeTest() throw(Exception)
{
LoggerPtr root = Logger::getRootLogger();
LayoutPtr layout = new SimpleLayout();
VectorAppenderPtr vectorAppender = new VectorAppender();
AsyncAppenderPtr asyncAppender = new AsyncAppender();
asyncAppender->setName(_T("async-CloseTest"));
asyncAppender->addAppender(vectorAppender);
root->addAppender(asyncAppender);
root->debug(_T("m1"));
asyncAppender->close();
root->debug(_T("m2"));
const std::vector<spi::LoggingEventPtr>& v = vectorAppender->getVector();
CPPUNIT_ASSERT(v.size() == 1);
}
// this test checks whether appenders embedded within an AsyncAppender are also
// closed
void test2()
{
LoggerPtr root = Logger::getRootLogger();
LayoutPtr layout = new SimpleLayout();
VectorAppenderPtr vectorAppender = new VectorAppender();
AsyncAppenderPtr asyncAppender = new AsyncAppender();
asyncAppender->setName(_T("async-test2"));
asyncAppender->addAppender(vectorAppender);
root->addAppender(asyncAppender);
root->debug(_T("m1"));
asyncAppender->close();
root->debug(_T("m2"));
const std::vector<spi::LoggingEventPtr>& v = vectorAppender->getVector();
CPPUNIT_ASSERT(v.size() == 1);
CPPUNIT_ASSERT(vectorAppender->isClosed());
}
// this test checks whether appenders embedded within an AsyncAppender are also
// closed
void test3()
{
typedef std::vector<spi::LoggingEventPtr>::size_type size_type;
size_type LEN = 200;
LoggerPtr root = Logger::getRootLogger();
LayoutPtr layout = new SimpleLayout();
VectorAppenderPtr vectorAppender = new VectorAppender();
AsyncAppenderPtr asyncAppender = new AsyncAppender();
asyncAppender->setName(_T("async-test3"));
asyncAppender->addAppender(vectorAppender);
root->addAppender(asyncAppender);
for (size_type i = 0; i < LEN; i++)
{
LOG4CXX_DEBUG(root, _T("message") << i);
}
asyncAppender->close();
root->debug(_T("m2"));
const std::vector<spi::LoggingEventPtr>& v = vectorAppender->getVector();
CPPUNIT_ASSERT(v.size() == LEN);
CPPUNIT_ASSERT(vectorAppender->isClosed());
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(AsyncAppenderTestCase);
--- NEW FILE: minimumtestcase.cpp ---
/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed 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 <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <log4cxx/logger.h>
#include <log4cxx/simplelayout.h>
#include <log4cxx/ttcclayout.h>
#include <log4cxx/fileappender.h>
#include <log4cxx/helpers/absolutetimedateformat.h>
#include "util/compare.h"
#include "util/transformer.h"
#include "util/linenumberfilter.h"
#include "util/controlfilter.h"
#include "util/absolutedateandtimefilter.h"
#include "util/threadfilter.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
#define FILTERED _T("output/filtered")
#define TTCC_PAT \
ABSOLUTE_DATE_AND_TIME_PAT \
_T(" \\[\\d*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message \\d{1,2}")
#define TTCC2_PAT \
ABSOLUTE_DATE_AND_TIME_PAT \
_T(" \\[\\d*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - ") \
_T("Messages should bear numbers 0 through 23\\.")
class MinimumTestCase : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(MinimumTestCase);
CPPUNIT_TEST(simple);
CPPUNIT_TEST(ttcc);
CPPUNIT_TEST_SUITE_END();
public:
void setUp()
{
root = Logger::getRootLogger();
root->removeAllAppenders();
}
void tearDown()
{
root->getLoggerRepository()->resetConfiguration();
}
void simple()
{
LayoutPtr layout = new SimpleLayout();
AppenderPtr appender = new FileAppender(layout, _T("output/simple"), false);
root->addAppender(appender);
common();
CPPUNIT_ASSERT(Compare::compare(_T("output/simple"), _T("witness/simple")));
}
void ttcc()
{
LayoutPtr layout =
new TTCCLayout(AbsoluteTimeDateFormat::DATE_AND_TIME_DATE_FORMAT);
AppenderPtr appender = new FileAppender(layout, _T("output/ttcc"), false);
root->addAppender(appender);
common();
ControlFilter filter1;
filter1 << TTCC_PAT << TTCC2_PAT;
AbsoluteDateAndTimeFilter filter2;
ThreadFilter filter3;
std::vector<Filter *> filters;
filters.push_back(&filter1);
filters.push_back(&filter2);
filters.push_back(&filter3);
try
{
Transformer::transform(_T("output/ttcc"), FILTERED, filters);
}
catch(UnexpectedFormatException& e)
{
tcout << _T("UnexpectedFormatException :") << e.getMessage() << std::endl;
throw;
}
CPPUNIT_ASSERT(Compare::compare(FILTERED, _T("witness/ttcc")));
}
void common()
{
int i = 0;
// In the lines below, the category names are chosen as an aid in
// remembering their level values. In general, the category names
// have no bearing to level values.
LoggerPtr ERR = Logger::getLogger(_T("ERR"));
ERR->setLevel(Level::ERROR);
LoggerPtr INF = Logger::getLogger(_T("INF"));
INF->setLevel(Level::INFO);
LoggerPtr INF_ERR = Logger::getLogger(_T("INF.ERR"));
INF_ERR->setLevel(Level::ERROR);
LoggerPtr DEB = Logger::getLogger(_T("DEB"));
DEB->setLevel(Level::DEBUG);
// Note: categories with undefined level
LoggerPtr INF_UNDEF = Logger::getLogger(_T("INF.UNDEF"));
LoggerPtr INF_ERR_UNDEF = Logger::getLogger(_T("INF.ERR.UNDEF"));
LoggerPtr UNDEF = Logger::getLogger(_T("UNDEF"));
// These should all log.----------------------------
LOG4CXX_FATAL(ERR, _T("Message ") << i);
i++; //0
LOG4CXX_ERROR(ERR, _T("Message ") << i);
i++;
LOG4CXX_FATAL(INF, _T("Message ") << i);
i++; // 2
LOG4CXX_ERROR(INF, _T("Message ") << i);
i++;
LOG4CXX_WARN(INF, _T("Message ") << i);
i++;
LOG4CXX_INFO(INF, _T("Message ") << i);
i++;
LOG4CXX_FATAL(INF_UNDEF, _T("Message ") << i);
i++; //6
LOG4CXX_ERROR(INF_UNDEF, _T("Message ") << i);
i++;
LOG4CXX_WARN(INF_UNDEF, _T("Message ") << i);
i++;
LOG4CXX_INFO(INF_UNDEF, _T("Message ") << i);
i++;
LOG4CXX_FATAL(INF_ERR, _T("Message ") << i);
i++; // 10
LOG4CXX_ERROR(INF_ERR, _T("Message ") << i);
i++;
LOG4CXX_FATAL(INF_ERR_UNDEF, _T("Message ") << i);
i++;
LOG4CXX_ERROR(INF_ERR_UNDEF, _T("Message ") << i);
i++;
LOG4CXX_FATAL(DEB, _T("Message ") << i);
i++; //14
LOG4CXX_ERROR(DEB, _T("Message ") << i);
i++;
LOG4CXX_WARN(DEB, _T("Message ") << i);
i++;
LOG4CXX_INFO(DEB, _T("Message ") << i);
i++;
LOG4CXX_DEBUG(DEB, _T("Message ") << i);
i++;
// defaultLevel=DEBUG
LOG4CXX_FATAL(UNDEF, _T("Message ") << i);
i++; // 19
LOG4CXX_ERROR(UNDEF, _T("Message ") << i);
i++;
LOG4CXX_WARN(UNDEF, _T("Message ") << i);
i++;
LOG4CXX_INFO(UNDEF, _T("Message ") << i);
i++;
LOG4CXX_DEBUG(UNDEF, _T("Message ") << i);
i++;
// -------------------------------------------------
// The following should not log
LOG4CXX_WARN(ERR, _T("Message ") << i);
i++;
LOG4CXX_INFO(ERR, _T("Message ") << i);
i++;
LOG4CXX_DEBUG(ERR, _T("Message ") << i);
i++;
LOG4CXX_DEBUG(INF, _T("Message ") << i);
i++;
LOG4CXX_DEBUG(INF_UNDEF, _T("Message ") << i);
i++;
LOG4CXX_WARN(INF_ERR, _T("Message ") << i);
i++;
LOG4CXX_INFO(INF_ERR, _T("Message ") << i);
i++;
LOG4CXX_DEBUG(INF_ERR, _T("Message ") << i);
i++;
LOG4CXX_WARN(INF_ERR_UNDEF, _T("Message ") << i);
i++;
LOG4CXX_INFO(INF_ERR_UNDEF, _T("Message ") << i);
i++;
LOG4CXX_DEBUG(INF_ERR_UNDEF, _T("Message ") << i);
i++;
// -------------------------------------------------
LOG4CXX_INFO(INF, _T("Messages should bear numbers 0 through 23."));
}
LoggerPtr root;
LoggerPtr logger;
};
CPPUNIT_TEST_SUITE_REGISTRATION(MinimumTestCase);
--- NEW FILE: hierarchythresholdtestcase.cpp ---
/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed 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 <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <log4cxx/logger.h>
#include <log4cxx/propertyconfigurator.h>
#include "util/compare.h"
#include "xml/xlevel.h"
using namespace log4cxx;
/**
Test the configuration of the hierarchy-wide threshold.
*/
class HierarchyThresholdTestCase : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(HierarchyThresholdTestCase);
CPPUNIT_TEST(test1);
CPPUNIT_TEST(test2);
CPPUNIT_TEST(test3);
CPPUNIT_TEST(test4);
CPPUNIT_TEST(test5);
CPPUNIT_TEST(test6);
CPPUNIT_TEST(test7);
CPPUNIT_TEST(test8);
CPPUNIT_TEST_SUITE_END();
public:
void setUp()
{
}
void tearDown()
{
logger->getLoggerRepository()->resetConfiguration();
}
void test1()
{
PropertyConfigurator::configure(_T("input/hierarchyThreshold1.properties"));
common();
CPPUNIT_ASSERT(Compare::compare(TEMP, _T("witness/hierarchyThreshold.1")));
}
void test2()
{
PropertyConfigurator::configure(_T("input/hierarchyThreshold2.properties"));
common();
CPPUNIT_ASSERT(Compare::compare(TEMP, _T("witness/hierarchyThreshold.2")));
}
void test3()
{
PropertyConfigurator::configure(_T("input/hierarchyThreshold3.properties"));
common();
CPPUNIT_ASSERT(Compare::compare(TEMP, _T("witness/hierarchyThreshold.3")));
}
void test4()
{
PropertyConfigurator::configure(_T("input/hierarchyThreshold4.properties"));
common();
CPPUNIT_ASSERT(Compare::compare(TEMP, _T("witness/hierarchyThreshold.4")));
}
void test5()
{
PropertyConfigurator::configure(_T("input/hierarchyThreshold5.properties"));
common();
CPPUNIT_ASSERT(Compare::compare(TEMP, _T("witness/hierarchyThreshold.5")));
}
void test6()
{
PropertyConfigurator::configure(_T("input/hierarchyThreshold6.properties"));
common();
CPPUNIT_ASSERT(Compare::compare(TEMP, _T("witness/hierarchyThreshold.6")));
}
void test7()
{
PropertyConfigurator::configure(_T("input/hierarchyThreshold7.properties"));
common();
CPPUNIT_ASSERT(Compare::compare(TEMP, _T("witness/hierarchyThreshold.7")));
}
void test8()
{
PropertyConfigurator::configure(_T("input/hierarchyThreshold8.properties"));
common();
CPPUNIT_ASSERT(Compare::compare(TEMP, _T("witness/hierarchyThreshold.8")));
}
static void common()
{
logger->log(XLevel::TRACE, _T("m0"));
logger->debug(_T("m1"));
logger->info(_T("m2"));
logger->warn(_T("m3"));
logger->error(_T("m4"));
logger->fatal(_T("m5"));
}
private:
static String TEMP;
static LoggerPtr logger;
};
String HierarchyThresholdTestCase::TEMP =
_T("output/temp");
LoggerPtr HierarchyThresholdTestCase::logger =
Logger::getLogger(_T("HierarchyThresholdTestCase"));
CPPUNIT_TEST_SUITE_REGISTRATION(HierarchyThresholdTestCase);
--- NEW FILE: shortsocketserver.cpp ---
/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed 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/logger.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/serversocket.h>
#include <log4cxx/mdc.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/helpers/inetaddress.h>
#include <log4cxx/helpers/socket.h>
#include <log4cxx/net/socketnode.h>
#include <log4cxx/helpers/thread.h>
#include "net/socketservertestcase.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::net;
class ShortSocketServer
{
static LoggerPtr logger;
public:
static void main(int argc, char **argv)
{
int totalTests = 0;
String prefix;
if (argc == 3)
{
USES_CONVERSION
totalTests = OptionConverter::toInt(A2T(argv[1]), totalTests);
prefix = A2T(argv[2]);
}
else
{
usage(argv[0], "Wrong number of arguments.");
}
LOGLOG_DEBUG(_T("Listening on port ") << PORT);
ServerSocket serverSocket(PORT);
MDC::put(_T("hostID"), _T("shortSocketServer"));
for (int i = 1; i <= totalTests; i++)
{
StringBuffer sbuf;
sbuf << prefix << i << _T(".properties");
PropertyConfigurator::configure(sbuf.str());
LOGLOG_DEBUG(_T("Waiting to accept a new client."));
SocketPtr socket = serverSocket.accept();
LOGLOG_DEBUG(_T("Connected to client at ") <<
socket->getInetAddress().toString());
LOGLOG_DEBUG(_T("Starting new socket node."));
SocketNodePtr sn = new SocketNode(socket, LogManager::getLoggerRepository());
ThreadPtr t = new Thread(sn);
t->start();
t->join();
}
}
static void usage(const char * programName, const char * msg)
{
std::cout << msg << std::endl;
std::cout << "Usage: " << programName;
std::cout << " totalTests configFilePrefix" << std::endl;
exit(1);
}
};
LoggerPtr ShortSocketServer::logger =
Logger::getLogger(_T("org.apache.log4j.net.ShortSocketServer"));
int main(int argc, char **argv)
{
int result = EXIT_SUCCESS;
try
{
ShortSocketServer::main(argc, argv);
}
catch(Exception&)
{
result = EXIT_FAILURE;
}
return result;
}
--- NEW FILE: vectorappender.h ---
/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed 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/appenderskeleton.h>
#include <vector>
#include <log4cxx/spi/loggingevent.h>
namespace log4cxx
{
class VectorAppender;
typedef helpers::ObjectPtrT<VectorAppender> VectorAppenderPtr;
/**
An appender that appends logging events to a vector.
*/
class VectorAppender : public AppenderSkeleton
{
public:
DECLARE_LOG4CXX_OBJECT(VectorAppender)
std::vector<spi::LoggingEventPtr> vector;
/**
Does nothing.
*/
void activateOptions() {}
/**
This method is called by the AppenderSkeleton#doAppend
method.
*/
void append(const spi::LoggingEventPtr& event);
const std::vector<spi::LoggingEventPtr>& getVector() const
{ return vector; }
void close();
bool isClosed() const
{ return closed; }
bool requiresLayout() const
{ return false; }
};
}
--- NEW FILE: vectorappender.cpp ---
/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed 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 "vectorappender.h"
#include <log4cxx/helpers/thread.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(VectorAppender)
void VectorAppender::append(const spi::LoggingEventPtr& event)
{
try
{
Thread::sleep(5);
}
catch (Exception&)
{
}
vector.push_back(event);
}
void VectorAppender::close()
{
if (this->closed)
{
return;
}
this->closed = true;
}
--- NEW FILE: Makefile.am ---
SUBDIRS = customlogger defaultinit helpers net pattern util varia xml
EXTRA_DIST = $(top_srcdir)/tests/src/*.cpp
noinst_HEADERS= $(top_srcdir)/tests/src/*.h
if TESTS
INCLUDES = -I$(top_srcdir)/include
noinst_PROGRAMS = testsuite shortsocketserver
testsuite_SOURCES = \
asyncappendertestcase.cpp\
drfatestcase.cpp\
hierarchythresholdtestcase.cpp\
l7dtestcase.cpp\
loggertestcase.cpp\
main.cpp\
minimumtestcase.cpp\
patternlayouttest.cpp\
vectorappender.cpp
testsuite_LDADD = \
$(top_builddir)/src/liblog4cxx.la
testsuite_LDFLAGS = \
-Wl,--whole-archive,customlogger/libcustomlogger.a,--no-whole-archive\
-Wl,--whole-archive,defaultinit/libdefaultinit.a,--no-whole-archive\
-Wl,--whole-archive,helpers/libhelpers.a,--no-whole-archive\
-Wl,--whole-archive,net/libnet.a,--no-whole-archive\
-Wl,--whole-archive,pattern/libpattern.a,--no-whole-archive\
-Wl,--whole-archive,util/libutil.a,--no-whole-archive\
-Wl,--whole-archive,varia/libvaria.a,--no-whole-archive\
-Wl,--whole-archive,xml/libxml.a,--no-whole-archive\
@LIBS_CPPUNIT@ -lboost_regex
AM_CPPFLAGS = @CPPFLAGS_CPPUNIT@
testsuite_DEPENDENCIES = \
customlogger/libcustomlogger.a\
defaultinit/libdefaultinit.a\
helpers/libhelpers.a\
net/libnet.a\
pattern/libpattern.a\
util/libutil.a\
varia/libvaria.a\
xml/libxml.a\
$(top_builddir)/src/liblog4cxx.la
shortsocketserver_SOURCES = \
shortsocketserver.cpp
shortsocketserver_LDADD = \
$(top_builddir)/src/liblog4cxx.la
shortsocketserver_LDFLAGS = \
-Wl,--whole-archive,util/libutil.a,--no-whole-archive\
-Wl,--whole-archive,xml/libxml.a,--no-whole-archive\
@LIBS_CPPUNIT@ -lboost_regex
shortsocketserver_DEPENDENCIES = \
util/libutil.a\
xml/libxml.a\
$(top_builddir)/src/liblog4cxx.la
check: testsuite shortsocketserver
endif
--- NEW FILE: drfatestcase.cpp ---
/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed 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 <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <log4cxx/dailyrollingfileappender.h>
#include <time.h>
#include <log4cxx/helpers/timezone.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
/**
Test the configuration of the hierarchy-wide threshold.
*/
class DRFATestCase : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(DRFATestCase);
CPPUNIT_TEST(testComputeCheckPeriod);
CPPUNIT_TEST(testRC1);
CPPUNIT_TEST(testRC2);
CPPUNIT_TEST_SUITE_END();
public:
void setUp()
{
}
void tearDown()
{
}
void testComputeCheckPeriod()
{
RollingCalendar rc;
CPPUNIT_ASSERT_EQUAL(RollingCalendar::TOP_OF_DAY,
rc.computeTriggeringPeriod(_T("%Y-%m-%d.log")));
CPPUNIT_ASSERT_EQUAL(RollingCalendar::TOP_OF_MINUTE,
rc.computeTriggeringPeriod(_T("%Y-%m-%d %M.log")));
CPPUNIT_ASSERT_EQUAL(RollingCalendar::TOP_OF_HOUR,
rc.computeTriggeringPeriod(_T("%Y-%m-%d %H.log")));
CPPUNIT_ASSERT_EQUAL(RollingCalendar::TOP_OF_MONTH,
rc.computeTriggeringPeriod(_T("%Y-%m.log")));
CPPUNIT_ASSERT_EQUAL(RollingCalendar::TOP_OF_HOUR,
rc.computeTriggeringPeriod(_T("log%Hlog")));
}
void testRC1()
{
RollingCalendar rc;
rc.setType(RollingCalendar::TOP_OF_DAY);
putenv("TZ=");
tzset();
// jan, mar, may, july, aug, oct, dec have 31 days
int M31[] = { 0, 2, 4, 6, 7, 9, 11 };
for (int i = 0; i < sizeof(M31)/sizeof(M31[0]); i++)
{
for (int d = 1; d <= 31; d++)
{
for (int h = 0; h < 23; h++)
{
struct tm tm;
memset(&tm, 0, sizeof(tm));
tm.tm_year = 80;
tm.tm_mon = M31[i];
tm.tm_mday = d;
tm.tm_hour = h;
tm.tm_min = 10;
tm.tm_sec = 10;
time_t buff = mktime(&tm);
int64_t t = int64_t(buff) * 1000;
t += 88;
int64_t t1 = rc.getNextCheckMillis(t);
time_t n = (time_t)(t1 / 1000);
struct tm * nextTime = localtime(&n);
if (d == 31)
{
CPPUNIT_ASSERT_EQUAL((M31[i] + 1) % 12, nextTime->tm_mon);
CPPUNIT_ASSERT_EQUAL(1, nextTime->tm_mday);
}
else
{
CPPUNIT_ASSERT_EQUAL(M31[i], nextTime->tm_mon);
CPPUNIT_ASSERT_EQUAL(d + 1, nextTime->tm_mday);
}
CPPUNIT_ASSERT_EQUAL(0, nextTime->tm_hour);
CPPUNIT_ASSERT_EQUAL(0, nextTime->tm_min);
CPPUNIT_ASSERT_EQUAL(0, nextTime->tm_sec);
CPPUNIT_ASSERT(0 == (t1 % 1000));
}
}
}
}
void testRC2()
{
RollingCalendar rc;
rc.setType(RollingCalendar::TOP_OF_HOUR);
TimeZonePtr timeZone = rc.getTimeZone();
putenv("TZ=");
tzset();
// jan, mar, may, july, aug, oct, dec have 31 days
int M31[] = { 0, 2, 4, 6, 7, 9, 11 };
for (int i = 0; i < sizeof(M31)/sizeof(M31[0]); i++)
{
for (int d = 1; d <= 31; d++)
{
for (int h = 0; h < 23; h++)
{
for (int m = 0; m <= 59; m++)
{
struct tm tm;
memset(&tm, 0, sizeof(tm));
tm.tm_year = 80;
tm.tm_mon = M31[i];
tm.tm_mday = d;
tm.tm_hour = h;
tm.tm_min = m;
tm.tm_sec = 12;
time_t buff = mktime(&tm);
int64_t t = int64_t(buff) * 1000;
t += 88;
bool dltState0 = timeZone->inDaylightTime(t);
t = rc.getNextCheckMillis(t);
bool dltState1 = timeZone->inDaylightTime(t);
time_t n = (time_t)(t / 1000);
struct tm * nextTime = localtime(&n);
CPPUNIT_ASSERT(0 == (t % 1000));
CPPUNIT_ASSERT_EQUAL(0, nextTime->tm_sec);
CPPUNIT_ASSERT_EQUAL(0, nextTime->tm_min);
if (dltState0 == dltState1)
{
CPPUNIT_ASSERT_EQUAL((tm.tm_hour + 1) % 24, nextTime->tm_hour);
}
else
{
// returning to standard time
if (dltState0)
{
CPPUNIT_ASSERT_EQUAL(tm.tm_hour, nextTime->tm_hour);
}
else
{
// switching to day light saving time
}
}
if (tm.tm_hour == 23)
{
CPPUNIT_ASSERT_EQUAL(d % 31 + 1, nextTime->tm_mday);
if (d == 31)
{
CPPUNIT_ASSERT_EQUAL((M31[i] + 1) % 12, nextTime->tm_mon);
}
else
{
CPPUNIT_ASSERT_EQUAL(M31[i], nextTime->tm_mon);
}
}
else
{
CPPUNIT_ASSERT_EQUAL(d, nextTime->tm_mday);
CPPUNIT_ASSERT_EQUAL(M31[i], nextTime->tm_mon);
}
}
}
}
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(DRFATestCase);
--- NEW FILE: l7dtestcase.cpp ---
/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed 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 <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <log4cxx/logger.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/helpers/propertyresourcebundle.h>
#include "util/compare.h"
#include <vector>
using namespace log4cxx;
using namespace log4cxx::helpers;
class L7dTestCase : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(L7dTestCase);
CPPUNIT_TEST(test1);
CPPUNIT_TEST_SUITE_END();
LoggerPtr root;
ResourceBundlePtr bundles[3];
public:
void setUp()
{
bundles[0] =
ResourceBundle::getBundle(_T("L7D"), Locale(_T("en"), _T("US")));
CPPUNIT_ASSERT(bundles[0] != 0);
bundles[1] =
ResourceBundle::getBundle(_T("L7D"), Locale(_T("fr"), _T("FR")));
CPPUNIT_ASSERT(bundles[1] != 0);
bundles[2] =
ResourceBundle::getBundle(_T("L7D"), Locale(_T("fr"), _T("CH")));
CPPUNIT_ASSERT(bundles[2] != 0);
root = Logger::getRootLogger();
}
void tearDown()
{
root->getLoggerRepository()->resetConfiguration();
}
void test1()
{
PropertyConfigurator::configure(_T("input/l7d1.properties"));
for (int i = 0; i < 3; i++)
{
root->setResourceBundle(bundles[i]);
LOG4CXX_L7DLOG(root, Level::DEBUG, _T("bogus1"));
LOG4CXX_L7DLOG(root, Level::INFO, _T("test"));
LOG4CXX_L7DLOG(root, Level::WARN, _T("hello_world"));
StringBuffer sbuf;
sbuf << (i+1);
LOG4CXX_L7DLOG2(root, Level::DEBUG, _T("msg1"), sbuf.str().c_str(),
_T("log4j"));
LOG4CXX_L7DLOG2(root, Level::ERROR, _T("bogusMsg"), sbuf.str().c_str(),
_T("log4j"));
LOG4CXX_L7DLOG2(root, Level::ERROR, _T("msg1"), sbuf.str().c_str(),
_T("log4j"));
LOG4CXX_L7DLOG(root, Level::INFO, _T("bogus2"));
}
CPPUNIT_ASSERT(Compare::compare(_T("output/temp"), _T("witness/l7d.1")));
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(L7dTestCase);
--- NEW FILE: loggertestcase.cpp ---
/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed 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 <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <log4cxx/logger.h>
#include <log4cxx/fileappender.h>
#include <log4cxx/appenderskeleton.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/level.h>
#include <log4cxx/hierarchy.h>
#include <log4cxx/spi/rootcategory.h>
#include <log4cxx/helpers/propertyresourcebundle.h>
using namespace log4cxx;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;
class CountingAppender;
typedef helpers::ObjectPtrT<CountingAppender> CountingAppenderPtr;
class CountingAppender : public AppenderSkeleton
{
public:
int counter;
CountingAppender() : counter(0)
{}
void close()
{}
void append(const spi::LoggingEventPtr& event)
{ counter++; }
bool requiresLayout() const
{ return true; }
};
class LoggerTestCase : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(LoggerTestCase);
CPPUNIT_TEST(testAppender1);
CPPUNIT_TEST(testAppender2);
CPPUNIT_TEST(testAdditivity1);
CPPUNIT_TEST(testAdditivity2);
CPPUNIT_TEST(testAdditivity3);
CPPUNIT_TEST(testDisable1);
CPPUNIT_TEST(testRB1);
CPPUNIT_TEST(testRB2);
CPPUNIT_TEST(testRB3);
CPPUNIT_TEST(testExists);
CPPUNIT_TEST(testHierarchy1);
CPPUNIT_TEST_SUITE_END();
public:
void setUp()
{
rbUS = PropertyResourceBundle::getBundle(_T("L7D"), Locale(_T("en"), _T("US")));
CPPUNIT_ASSERT(rbUS != 0);
rbFR = PropertyResourceBundle::getBundle(_T("L7D"), Locale(_T("fr"), _T("FR")));
CPPUNIT_ASSERT(rbFR != 0);
rbCH = PropertyResourceBundle::getBundle(_T("L7D"), Locale(_T("fr"), _T("CH")));
CPPUNIT_ASSERT(rbCH != 0);
}
void tearDown()
{
BasicConfigurator::resetConfiguration();
a1 = 0;
a2 = 0;
}
/**
Add an appender and see if it can be retrieved.
*/
void testAppender1()
{
logger = Logger::getLogger(_T("test"));
a1 = new FileAppender();
a1->setName(_T("testAppender1"));
logger->addAppender(a1);
AppenderList list = logger->getAllAppenders();
AppenderPtr aHat = list.front();
CPPUNIT_ASSERT_EQUAL(a1, aHat);
}
/**
Add an appender X, Y, remove X and check if Y is the only
remaining appender.
*/
void testAppender2()
{
a1 = new FileAppender();
a1->setName(_T("testAppender2.1"));
a2 = new FileAppender();
a2->setName(_T("testAppender2.2"));
logger = Logger::getLogger(_T("test"));
logger->addAppender(a1);
logger->addAppender(a2);
logger->removeAppender(String(_T("testAppender2.1")));
AppenderList list = logger->getAllAppenders();
AppenderPtr aHat = list.front();
CPPUNIT_ASSERT_EQUAL(a2, aHat);
CPPUNIT_ASSERT(list.size() == 1);
}
/**
Test if LoggerPtr a.b inherits its appender from a.
*/
void testAdditivity1()
{
LoggerPtr a = Logger::getLogger(_T("a"));
LoggerPtr ab = Logger::getLogger(_T("a.b"));
CountingAppenderPtr ca = new CountingAppender();
a->addAppender(ca);
CPPUNIT_ASSERT_EQUAL(ca->counter, 0);
ab->debug(MSG);
CPPUNIT_ASSERT_EQUAL(ca->counter, 1);
ab->info(MSG);
CPPUNIT_ASSERT_EQUAL(ca->counter, 2);
ab->warn(MSG);
CPPUNIT_ASSERT_EQUAL(ca->counter, 3);
ab->error(MSG);
CPPUNIT_ASSERT_EQUAL(ca->counter, 4);
}
/**
Test multiple additivity.
*/
void testAdditivity2()
{
LoggerPtr a = Logger::getLogger(_T("a"));
LoggerPtr ab = Logger::getLogger(_T("a.b"));
LoggerPtr abc = Logger::getLogger(_T("a.b.c"));
LoggerPtr x = Logger::getLogger(_T("x"));
CountingAppenderPtr ca1 = new CountingAppender();
CountingAppenderPtr ca2 = new CountingAppender();
a->addAppender(ca1);
abc->addAppender(ca2);
CPPUNIT_ASSERT_EQUAL(ca1->counter, 0);
CPPUNIT_ASSERT_EQUAL(ca2->counter, 0);
ab->debug(MSG);
CPPUNIT_ASSERT_EQUAL(ca1->counter, 1);
CPPUNIT_ASSERT_EQUAL(ca2->counter, 0);
abc->debug(MSG);
CPPUNIT_ASSERT_EQUAL(ca1->counter, 2);
CPPUNIT_ASSERT_EQUAL(ca2->counter, 1);
x->debug(MSG);
CPPUNIT_ASSERT_EQUAL(ca1->counter, 2);
CPPUNIT_ASSERT_EQUAL(ca2->counter, 1);
}
/**
Test additivity flag.
*/
void testAdditivity3()
{
LoggerPtr root = Logger::getRootLogger();
LoggerPtr a = Logger::getLogger(_T("a"));
LoggerPtr ab = Logger::getLogger(_T("a.b"));
LoggerPtr abc = Logger::getLogger(_T("a.b.c"));
LoggerPtr x = Logger::getLogger(_T("x"));
CountingAppenderPtr caRoot = new CountingAppender();
CountingAppenderPtr caA = new CountingAppender();
CountingAppenderPtr caABC = new CountingAppender();
root->addAppender(caRoot);
a->addAppender(caA);
abc->addAppender(caABC);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 0);
CPPUNIT_ASSERT_EQUAL(caA->counter, 0);
CPPUNIT_ASSERT_EQUAL(caABC->counter, 0);
ab->setAdditivity(false);
a->debug(MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 1);
CPPUNIT_ASSERT_EQUAL(caA->counter, 1);
CPPUNIT_ASSERT_EQUAL(caABC->counter, 0);
ab->debug(MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 1);
CPPUNIT_ASSERT_EQUAL(caA->counter, 1);
CPPUNIT_ASSERT_EQUAL(caABC->counter, 0);
abc->debug(MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 1);
CPPUNIT_ASSERT_EQUAL(caA->counter, 1);
CPPUNIT_ASSERT_EQUAL(caABC->counter, 1);
}
void testDisable1()
{
CountingAppenderPtr caRoot = new CountingAppender();
LoggerPtr root = Logger::getRootLogger();
root->addAppender(caRoot);
LoggerRepositoryPtr h = LogManager::getLoggerRepository();
//h.disableDebug();
h->setThreshold(Level::INFO);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 0);
root->debug(MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 0);
root->info(MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 1);
root->log(Level::WARN, MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 2);
root->warn(MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 3);
//h.disableInfo();
h->setThreshold(Level::WARN);
root->debug(MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 3);
root->info(MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 3);
root->log(Level::WARN, MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 4);
root->error(MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 5);
root->log(Level::ERROR, MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 6);
//h.disableAll();
h->setThreshold(Level::OFF);
root->debug(MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->info(MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->log(Level::WARN, MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->error(MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->log(Level::FATAL, MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->log(Level::FATAL, MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 6);
//h.disable(Level::getFatalLevel());
h->setThreshold(Level::OFF);
root->debug(MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->info(MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->log(Level::WARN, MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->error(MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->log(Level::WARN, MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 6);
root->log(Level::FATAL, MSG);
CPPUNIT_ASSERT_EQUAL(caRoot->counter, 6);
}
void testRB1()
{
LoggerPtr root = Logger::getRootLogger();
root->setResourceBundle(rbUS);
ResourceBundlePtr t = root->getResourceBundle();
CPPUNIT_ASSERT(t == rbUS);
LoggerPtr x = Logger::getLogger(_T("x"));
LoggerPtr x_y = Logger::getLogger(_T("x.y"));
LoggerPtr x_y_z = Logger::getLogger(_T("x.y.z"));
t = x->getResourceBundle();
CPPUNIT_ASSERT(t == rbUS);
t = x_y->getResourceBundle();
CPPUNIT_ASSERT(t == rbUS);
t = x_y_z->getResourceBundle();
CPPUNIT_ASSERT(t == rbUS);
}
void testRB2()
{
LoggerPtr root = Logger::getRootLogger();
root->setResourceBundle(rbUS);
ResourceBundlePtr t = root->getResourceBundle();
CPPUNIT_ASSERT(t == rbUS);
LoggerPtr x = Logger::getLogger(_T("x"));
LoggerPtr x_y = Logger::getLogger(_T("x.y"));
LoggerPtr x_y_z = Logger::getLogger(_T("x.y.z"));
x_y->setResourceBundle(rbFR);
t = x->getResourceBundle();
CPPUNIT_ASSERT(t == rbUS);
t = x_y->getResourceBundle();
CPPUNIT_ASSERT(t == rbFR);
t = x_y_z->getResourceBundle();
CPPUNIT_ASSERT(t == rbFR);
}
void testRB3()
{
LoggerPtr root = Logger::getRootLogger();
root->setResourceBundle(rbUS);
ResourceBundlePtr t = root->getResourceBundle();
CPPUNIT_ASSERT(t == rbUS);
LoggerPtr x = Logger::getLogger(_T("x"));
LoggerPtr x_y = Logger::getLogger(_T("x.y"));
LoggerPtr x_y_z = Logger::getLogger(_T("x.y.z"));
x_y->setResourceBundle(rbFR);
x_y_z->setResourceBundle(rbCH);
t = x->getResourceBundle();
CPPUNIT_ASSERT(t == rbUS);
t = x_y->getResourceBundle();
CPPUNIT_ASSERT(t == rbFR);
t = x_y_z->getResourceBundle();
CPPUNIT_ASSERT(t == rbCH);
}
void testExists()
{
LoggerPtr a = Logger::getLogger(_T("a"));
LoggerPtr a_b = Logger::getLogger(_T("a.b"));
LoggerPtr a_b_c = Logger::getLogger(_T("a.b.c"));
LoggerPtr t;
t = LogManager::exists(_T("xx"));
CPPUNIT_ASSERT(t == 0);
t = LogManager::exists(_T("a"));
CPPUNIT_ASSERT_EQUAL(a, t);
t = LogManager::exists(_T("a.b"));
CPPUNIT_ASSERT_EQUAL(a_b, t);
t = LogManager::exists(_T("a.b.c"));
CPPUNIT_ASSERT_EQUAL(a_b_c, t);
}
void testHierarchy1()
{
LoggerRepositoryPtr h = new Hierarchy(new RootCategory(Level::ERROR));
LoggerPtr a0 = h->getLogger(_T("a"));
CPPUNIT_ASSERT(String(_T("a")) == a0->getName());
CPPUNIT_ASSERT(a0->getLevel() == 0);
CPPUNIT_ASSERT(Level::ERROR == a0->getEffectiveLevel());
LoggerPtr a1 = h->getLogger(_T("a"));
CPPUNIT_ASSERT_EQUAL(a0, a1);
}
protected:
static String MSG;
LoggerPtr logger;
AppenderPtr a1;
AppenderPtr a2;
ResourceBundlePtr rbUS;
ResourceBundlePtr rbFR;
ResourceBundlePtr rbCH;
};
String LoggerTestCase::MSG = _T("M");
CPPUNIT_TEST_SUITE_REGISTRATION(LoggerTestCase);
|