    1   /*
    2    * Licensed to the Apache Software Foundation (ASF) under one or more
    3    * contributor license agreements.  See the NOTICE file distributed with
    4    * this work for additional information regarding copyright ownership.
    5    * The ASF licenses this file to You under the Apache License, Version 2.0
    6    * (the "License"); you may not use this file except in compliance with
    7    * the License.  You may obtain a copy of the License at
    8    *
    9    *      http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  package org.apache.log4j;
    18
    19  import junit.framework.Assert;
    20
    21  import org.apache.log4j.Level;
    22  import org.apache.log4j.Logger;
    23  import org.apache.log4j.VectorAppender;
    24  import org.apache.log4j.spi.LoggingEvent;
    25
    26  import java.util.Vector;
    27
    28
    29  /**
    30   * Helper class to set up and capture log messages.
    31   */
    32  public class LogCapture {
    33      /**
    34       * Appender.
    35       */
    36      private final VectorAppender appender;
    37
    38      /**
    39       * Expected level.
    40       */
    41      private final Level level;
    42
    43      /**
    44       * Creates new instance of LogCapture.
    45       *
    46       */
    47      public LogCapture(final Level level) {
    48          this.level = level;
    49
    50          Logger root = Logger.getRootLogger();
    51          appender = new VectorAppender();
    52          root.addAppender(appender);
    53      }
    54
    55      /**
    56       * Get message.
    57       * @return rendered message, null if no logging event captured.
    58       */
    59      public String getMessage() {
    60          Vector vector = appender.getVector();
    61          String msg = null;
    62
    63          switch (vector.size()) {
    64          case 0:
    65              break;
    66
    67          case 1:
    68
    69              LoggingEvent event = (LoggingEvent) vector.elementAt(0);
    70              Assert.assertNotNull(event);
    71              Assert.assertEquals(level, event.getLevel());
    72              msg = event.getRenderedMessage();
    73
    74              break;
    75
    76          default:
    77              Assert.fail("More than one request captured");
    78          }
    79
    80          return msg;
    81      }
    82  }