001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018 package org.apache.logging.log4j.io;
019
020 import java.io.FilterReader;
021 import java.io.IOException;
022 import java.io.Reader;
023 import java.nio.CharBuffer;
024
025 import org.apache.logging.log4j.Level;
026 import org.apache.logging.log4j.Marker;
027 import org.apache.logging.log4j.spi.ExtendedLogger;
028
029 /**
030 * Logs each line read to a pre-defined level. Can also be configured with a Marker.
031 *
032 * @since 2.1
033 */
034 public class LoggerReader extends FilterReader {
035 private static final String FQCN = LoggerReader.class.getName();
036
037 private final CharStreamLogger logger;
038 private final String fqcn;
039
040 protected LoggerReader(final Reader reader, final ExtendedLogger logger, final String fqcn, final Level level,
041 final Marker marker) {
042 super(reader);
043 this.logger = new CharStreamLogger(logger, level, marker);
044 this.fqcn = fqcn == null ? FQCN : fqcn;
045 }
046
047 @Override
048 public void close() throws IOException {
049 super.close();
050 this.logger.close(this.fqcn);
051 }
052
053 @Override
054 public int read() throws IOException {
055 final int c = super.read();
056 this.logger.put(this.fqcn, c);
057 return c;
058 }
059
060 @Override
061 public int read(final char[] cbuf) throws IOException {
062 return read(cbuf, 0, cbuf.length);
063 }
064
065 @Override
066 public int read(final char[] cbuf, final int off, final int len) throws IOException {
067 final int charsRead = super.read(cbuf, off, len);
068 this.logger.put(this.fqcn, cbuf, off, charsRead);
069 return charsRead;
070 }
071
072 @Override
073 public int read(final CharBuffer target) throws IOException {
074 final int len = target.remaining();
075 final char[] cbuf = new char[len];
076 final int charsRead = read(cbuf, 0, len);
077 if (charsRead > 0) {
078 target.put(cbuf, 0, charsRead);
079 }
080 return charsRead;
081 }
082
083 @Override
084 public String toString() {
085 return LoggerReader.class.getSimpleName() + "{stream=" + this.in + '}';
086 }
087 }