サンプル5 testFilter.cpp

 フィルター(log4cpp::Filter)を使ったサンプルです。

関連ファイル
  • testFilter.cpp
ファイルの中身

testFilter.cpp

  1. #include <log4cpp/Filter.hh>
  2. #include <iostream>
  3. class TestFilter : public log4cpp::Filter {
  4. public:
  5. TestFilter() {};
  6. virtual ~TestFilter() {};
  7. protected:
  8. virtual log4cpp::Filter::Decision _decide(const log4cpp::LoggingEvent& event) {
  9. log4cpp::Filter::Decision decision = log4cpp::Filter::NEUTRAL;
  10. if (event.categoryName == "deny")
  11. decision = log4cpp::Filter::DENY;
  12. if (event.categoryName == "accept")
  13. decision = log4cpp::Filter::ACCEPT;
  14. return decision;
  15. };
  16. };
  17. class TestFilter2 : public log4cpp::Filter {
  18. public:
  19. TestFilter2() {};
  20. virtual ~TestFilter2() {};
  21. protected:
  22. virtual log4cpp::Filter::Decision _decide(const log4cpp::LoggingEvent& event) {
  23. log4cpp::Filter::Decision decision = log4cpp::Filter::NEUTRAL;
  24. if (event.ndc == "test")
  25. decision = log4cpp::Filter::DENY;
  26. return decision;
  27. };
  28. };
  29. int main(int argc, char** argv) {
  30. TestFilter filter;
  31. bool resultsOK = true;
  32. std::cout << "decision 1 (should be 1): " << filter.decide(log4cpp::LoggingEvent("accept", "bla", "ndc", log4cpp::Priority::INFO)) << std::endl;
  33. std::cout << "decision 2 (should be -1): " << filter.decide(log4cpp::LoggingEvent("deny", "bla", "ndc", log4cpp::Priority::INFO)) << std::endl;
  34. std::cout << "decision 3 (should be 0): " << filter.decide(log4cpp::LoggingEvent("neither", "bla", "ndc", log4cpp::Priority::INFO)) << std::endl;
  35. std::cout << "decision 4 (should be 0): " << filter.decide(log4cpp::LoggingEvent("neither", "bla", "test", log4cpp::Priority::INFO)) << std::endl;
  36. filter.setChainedFilter(new TestFilter2());
  37. std::cout << "decision 5 (should be 0): " << filter.decide(log4cpp::LoggingEvent("neither", "bla", "ndc", log4cpp::Priority::INFO)) << std::endl;
  38. std::cout << "decision 6 (should be -1): " << filter.decide(log4cpp::LoggingEvent("neither", "bla", "test", log4cpp::Priority::INFO)) << std::endl;
  39. return 0;
  40. }

実行結果例

 testFilter.cppをビルドし、実行した結果です。実行環境はLinux(Ubuntu 11.0)です。

stdout(標準出力):

decision 1 (should be 1): 1
decision 2 (should be -1): -1
decision 3 (should be 0): 0
decision 4 (should be 0): 0
decision 5 (should be 0): 0
decision 6 (should be -1): -1