1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package de.smartics.maven.util;
17
18 import java.lang.reflect.Method;
19 import java.util.logging.Level;
20
21 import org.apache.maven.plugin.logging.Log;
22
23
24
25
26
27
28
29 public final class LoggingUtils
30 {
31
32
33
34
35
36
37
38
39
40
41
42
43
44 private LoggingUtils()
45 {
46 }
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64 public static void configureLogger(final Log log, final String logLevel)
65 {
66 final String newLevel;
67 if (!isBlank(logLevel))
68 {
69 newLevel = logLevel;
70 if (log.isDebugEnabled())
71 {
72 log.debug("Using configured level " + newLevel);
73 }
74 }
75 else
76 {
77 newLevel = determineLevel(log);
78 if (log.isDebugEnabled())
79 {
80 log.debug("Using Maven level " + newLevel);
81 }
82 }
83 configure(log, newLevel);
84 }
85
86 private static void configure(final Log log, final String newLevel)
87 {
88 if (isAvailable("org.apache.log4j.Logger"))
89 {
90 runLog4jConfigure(log, newLevel);
91 }
92
93 new SunLoggerConfigurator().configure(log, newLevel);
94 }
95
96 private static void runLog4jConfigure(final Log log, final String newLevel)
97 {
98 try
99 {
100 final Class<?> clazz =
101 Class.forName("de.smartics.maven.util.log4j.Log4jConfigurator");
102 final Object instance = clazz.newInstance();
103 final Method method =
104 clazz.getMethod("configure", Log.class, String.class);
105 method.invoke(instance, log, newLevel);
106 }
107 catch (final Exception e)
108 {
109 if (log.isWarnEnabled())
110 {
111 log.warn("Cannot configure log4j logger.", e);
112 }
113 }
114 }
115
116 private static boolean isAvailable(final String className)
117 {
118 try
119 {
120 Class.forName(className);
121 return true;
122 }
123 catch (final Exception e)
124 {
125 return false;
126 }
127 }
128
129
130
131
132
133
134
135
136
137
138
139 private static boolean isBlank(final String logLevel)
140 {
141 return (logLevel == null || "".equals(logLevel.trim()));
142 }
143
144
145
146
147
148
149
150 private static String determineLevel(final Log log)
151 {
152 if (log.isDebugEnabled())
153 {
154 return Level.FINEST.toString();
155 }
156 else if (log.isInfoEnabled())
157 {
158 return Level.INFO.toString();
159 }
160 else if (log.isWarnEnabled())
161 {
162 return Level.WARNING.toString();
163 }
164 else
165 {
166 return Level.SEVERE.toString();
167 }
168 }
169
170
171
172 }