1 16 package org.apache.log4j; 17 18 import java.io.File ; 19 import java.io.Writer ; 20 import java.io.FileWriter ; 21 import java.io.BufferedWriter ; 22 import org.apache.log4j.spi.LoggingEvent; 23 import org.apache.log4j.helpers.OptionConverter; 24 import org.apache.log4j.spi.ErrorHandler; 25 26 33 public class TempFileAppender extends AppenderSkeleton { 34 35 41 static final public String PATH_OPTION = "Path"; 42 43 46 protected String path = null; 47 48 53 static final public String PREFIX_OPTION = "Prefix"; 54 55 58 protected String prefix = "l4j_"; 59 60 65 static final public String SUFFIX_OPTION = "Suffix"; 66 67 70 protected String suffix = ".tmp"; 71 72 75 76 protected File dir = null; 77 78 79 80 81 84 public TempFileAppender() { 85 super(); 86 } 87 88 91 public String [] getOptionStrings() { 92 return OptionConverter.concatanateArrays(super.getOptionStrings(), 93 new String [] {PATH_OPTION,PREFIX_OPTION,SUFFIX_OPTION}); 94 } 95 96 105 106 public void setOption(String key, String value) { 107 super.setOption(key, value); 108 if(key.equalsIgnoreCase(PATH_OPTION)) { 109 path = value; 110 if(path==null) { 111 errorHandler.error("Path cannot be empty!",null,0); 112 } 113 114 dir = new File (path); 115 if(!(dir.exists() && dir.isDirectory() && dir.canWrite())) { 116 errorHandler.error("Cannot write to directory " + path + "!",null,0); 117 } 118 } 119 else if(key.equalsIgnoreCase(PREFIX_OPTION)) { 120 if(value!=null && value.length()>=3) { 121 prefix = value; 122 } else { 123 errorHandler.error("Prefix cannot be shorter than 3 characters!", 124 null,0); 125 } 126 } 127 else if(key.equalsIgnoreCase(SUFFIX_OPTION)) { 128 if(value!=null && value.length()>=1) { 129 suffix = value; 130 } else { 131 errorHandler.error("Suffix cannot be empty!",null,0); 132 } 133 } 134 } 135 136 147 public void append(LoggingEvent event) { 148 if(!checkEntryConditions()) { 149 return; 150 } 151 subAppend(event); 152 } 153 154 157 protected boolean checkEntryConditions() { 158 return true; 159 } 160 161 164 protected void subAppend(LoggingEvent event) { 165 try { 166 File tmp = File.createTempFile(prefix,suffix,dir); 167 Writer out = new BufferedWriter (new FileWriter (tmp)); 168 out.write(event.message); 169 out.close(); 170 171 } catch (Exception e) { 172 errorHandler.error("Error during creation of temporary File!",e,1); 173 } 174 } 175 176 public boolean requiresLayout() { 177 return false; 178 } 179 180 public void close() { 181 182 } 183 } 184 198 | Popular Tags |