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.util.LinkedList; 023 import java.util.Queue; 024 025 import org.apache.hadoop.classification.InterfaceAudience.Public; 026 import org.apache.hadoop.classification.InterfaceStability.Unstable; 027 import org.apache.log4j.FileAppender; 028 import org.apache.log4j.spi.LoggingEvent; 029 030 /** 031 * A simple log4j-appender for container's logs. 032 * 033 */ 034 @Public 035 @Unstable 036 public class ContainerLogAppender extends FileAppender { 037 private String containerLogDir; 038 //so that log4j can configure it from the configuration(log4j.properties). 039 private int maxEvents; 040 private Queue<LoggingEvent> tail = null; 041 042 @Override 043 public void activateOptions() { 044 synchronized (this) { 045 if (maxEvents > 0) { 046 tail = new LinkedList<LoggingEvent>(); 047 } 048 setFile(new File(this.containerLogDir, "syslog").toString()); 049 setAppend(true); 050 super.activateOptions(); 051 } 052 } 053 054 @Override 055 public void append(LoggingEvent event) { 056 synchronized (this) { 057 if (tail == null) { 058 super.append(event); 059 } else { 060 if (tail.size() >= maxEvents) { 061 tail.remove(); 062 } 063 tail.add(event); 064 } 065 } 066 } 067 068 public void flush() { 069 if (qw != null) { 070 qw.flush(); 071 } 072 } 073 074 @Override 075 public synchronized void close() { 076 if (tail != null) { 077 for(LoggingEvent event: tail) { 078 super.append(event); 079 } 080 } 081 super.close(); 082 } 083 084 /** 085 * Getter/Setter methods for log4j. 086 */ 087 088 public String getContainerLogDir() { 089 return this.containerLogDir; 090 } 091 092 public void setContainerLogDir(String containerLogDir) { 093 this.containerLogDir = containerLogDir; 094 } 095 096 private static final int EVENT_SIZE = 100; 097 098 public long getTotalLogFileSize() { 099 return maxEvents * EVENT_SIZE; 100 } 101 102 public void setTotalLogFileSize(long logSize) { 103 maxEvents = (int) logSize / EVENT_SIZE; 104 } 105 }