1 package org.kuali.ole.sys.context;
2
3 import java.util.Enumeration;
4
5 import org.apache.log4j.Appender;
6 import org.apache.log4j.ConsoleAppender;
7 import org.apache.log4j.Layout;
8 import org.apache.log4j.Logger;
9 import org.apache.log4j.PatternLayout;
10
11
12
13
14 public class BatchLogger {
15 public static final String DEFAULT_CONVERSION_PATTERN = "%d [%t] u:%X{user}/d:%X{docId} %-5p %c :: %m%n";
16 public static final Layout DEFAULT_PATTERN_LAYOUT = new PatternLayout(DEFAULT_CONVERSION_PATTERN);
17 public static final String LOG_FILE_APPENDER_NAME = "LogFile";
18
19
20
21
22
23
24
25 public static void addConsoleAppender(Logger logger) {
26 if (!isConsoleAppenderExists(logger)) {
27
28 Appender console = new ConsoleAppender(getLogFileAppenderLayout(logger));
29
30 logger.addAppender(console);
31 }
32 }
33
34
35
36
37
38
39 public static Layout getLogFileAppenderLayout() {
40 return getLogFileAppenderLayout(null);
41 }
42
43
44
45
46
47
48
49 private static boolean isConsoleAppenderExists(Logger logger) {
50 Enumeration<Appender> rootAppenders = Logger.getRootLogger().getAllAppenders();
51 while(rootAppenders.hasMoreElements()) {
52 Appender appender = rootAppenders.nextElement();
53 if (appender instanceof ConsoleAppender) {
54 return true;
55 }
56 }
57
58 Enumeration<Appender> appenders = logger.getAllAppenders();
59 while(appenders.hasMoreElements()) {
60 Appender appender = appenders.nextElement();
61 if (appender instanceof ConsoleAppender) {
62 return true;
63 }
64 }
65 return false;
66 }
67
68
69
70
71 private static Appender getLogFileAppender(Logger logger) {
72 if (Logger.getRootLogger() != null) {
73 return Logger.getRootLogger().getAppender(LOG_FILE_APPENDER_NAME);
74 }
75 else if (logger != null ) {
76 return logger.getAppender(LOG_FILE_APPENDER_NAME);
77 }
78 return null;
79 }
80
81
82
83
84
85
86
87 private static Layout getLogFileAppenderLayout(Logger logger) {
88 Appender logFileAppender = getLogFileAppender(logger);
89
90 if (logFileAppender != null) {
91 return logFileAppender.getLayout();
92 }
93 else {
94 System.out.println(BatchLogger.class.getName() +": Could not find '"+ LOG_FILE_APPENDER_NAME +"' appender on RootLogger. Using DEFAULT_CONVERSION_PATTERN for layout to console");
95 return DEFAULT_PATTERN_LAYOUT;
96 }
97 }
98 }