Setting file appender log path on runtime


/ Published in: Java
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import com.alphacsp.common.log.Log;
  2. import org.apache.log4j.Category;
  3. import org.apache.log4j.FileAppender;
  4. import org.apache.log4j.AppenderSkeleton;
  5.  
  6. import java.lang.reflect.Field;
  7. import java.util.Enumeration;
  8.  
  9. public class FileAppenderManipulation {
  10.  
  11. public void setAppenderFilenameForLogger(Log log, String filename, String appenderName) {
  12. try {
  13. Category category = getCategory(log);
  14. final FileAppender fileAppender = (FileAppender) locateAppender(category, appenderName);
  15. fileAppender.setFile(filename);
  16. fileAppender.activateOptions();
  17. } catch (NoSuchFieldException e) {
  18. e.printStackTrace();
  19. } catch (IllegalAccessException e) {
  20. e.printStackTrace();
  21. }
  22.  
  23. }
  24.  
  25. private AppenderSkeleton locateAppender(Category category, String name) {
  26. do {
  27. final Enumeration appenders = category.getAllAppenders();
  28. while (appenders.hasMoreElements()) {
  29. AppenderSkeleton appenderSkeleton = (AppenderSkeleton) appenders.nextElement();
  30. if (appenderSkeleton.getName().equals(name)) {
  31. return appenderSkeleton;
  32. }
  33. }
  34. } while ((category = category.getParent()) != null);
  35. throw new RuntimeException("The requested appender dosn't exists!");
  36. }
  37.  
  38. private Category getCategory(Log log) throws NoSuchFieldException, IllegalAccessException {
  39. Field field = log.getClass().getDeclaredField("category");
  40. field.setAccessible(true);
  41. Category category = (Category) field.get(log);
  42. return category;
  43. }
  44. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.