001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019 package org.apache.hadoop.yarn;
020
021 import java.io.File;
022 import java.io.Flushable;
023 import java.util.LinkedList;
024 import java.util.Queue;
025
026 import org.apache.hadoop.classification.InterfaceAudience.Public;
027 import org.apache.hadoop.classification.InterfaceStability.Unstable;
028 import org.apache.log4j.FileAppender;
029 import org.apache.log4j.spi.LoggingEvent;
030
031 /**
032 * A simple log4j-appender for container's logs.
033 *
034 */
035 @Public
036 @Unstable
037 public class ContainerLogAppender extends FileAppender
038 implements Flushable
039 {
040 private String containerLogDir;
041 //so that log4j can configure it from the configuration(log4j.properties).
042 private int maxEvents;
043 private Queue<LoggingEvent> tail = null;
044
045 @Override
046 public void activateOptions() {
047 synchronized (this) {
048 if (maxEvents > 0) {
049 tail = new LinkedList<LoggingEvent>();
050 }
051 setFile(new File(this.containerLogDir, "syslog").toString());
052 setAppend(true);
053 super.activateOptions();
054 }
055 }
056
057 @Override
058 public void append(LoggingEvent event) {
059 synchronized (this) {
060 if (tail == null) {
061 super.append(event);
062 } else {
063 if (tail.size() >= maxEvents) {
064 tail.remove();
065 }
066 tail.add(event);
067 }
068 }
069 }
070
071 @Override
072 public void flush() {
073 if (qw != null) {
074 qw.flush();
075 }
076 }
077
078 @Override
079 public synchronized void close() {
080 if (tail != null) {
081 for(LoggingEvent event: tail) {
082 super.append(event);
083 }
084 }
085 super.close();
086 }
087
088 /**
089 * Getter/Setter methods for log4j.
090 */
091
092 public String getContainerLogDir() {
093 return this.containerLogDir;
094 }
095
096 public void setContainerLogDir(String containerLogDir) {
097 this.containerLogDir = containerLogDir;
098 }
099
100 private static final int EVENT_SIZE = 100;
101
102 public long getTotalLogFileSize() {
103 return maxEvents * EVENT_SIZE;
104 }
105
106 public void setTotalLogFileSize(long logSize) {
107 maxEvents = (int) logSize / EVENT_SIZE;
108 }
109 }