View Javadoc
1   /**
2    *    Copyright 2006-2016 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.mybatis.generator.logging;
17  
18  import static org.mybatis.generator.internal.util.messages.Messages.getString;
19  
20  import org.mybatis.generator.internal.ObjectFactory;
21  
22  /**
23   * Factory for creating loggers. Uses runtime introspection to determine the
24   * AbstractLogFactory implementation.
25   * 
26   * @author Jeff Butler
27   * 
28   */
29  public class LogFactory {
30      private static AbstractLogFactory logFactory;
31  
32      static {
33          try {
34              ObjectFactory.internalClassForName("org.apache.log4j.Logger"); //$NON-NLS-1$
35              logFactory = new Log4jLoggingLogFactory();
36          } catch (Exception e) {
37              logFactory = new JdkLoggingLogFactory();
38          }
39      }
40  
41      public static Log getLog(Class<?> clazz) {
42          try {
43              return logFactory.getLog(clazz);
44          } catch (Throwable t) {
45              throw new RuntimeException(getString("RuntimeError.21", //$NON-NLS-1$
46                      clazz.getName(), t.getMessage()), t);
47          }
48      }
49  
50      /**
51       * This method will switch the logging implementation to Java native
52       * logging. This is useful in situations where you want to use Java native
53       * logging to log activity but Log4J is on the classpath. Note that
54       * this method is only effective for log classes obtained after calling this
55       * method. If you intend to use this method you should call it before
56       * calling any other method.
57       */
58      public static synchronized void forceJavaLogging() {
59          logFactory = new JdkLoggingLogFactory();
60      }
61  
62      private static class JdkLoggingLogFactory implements AbstractLogFactory {
63          public Log getLog(Class<?> clazz) {
64              return new JdkLoggingImpl(clazz);
65          }
66      }
67  
68      private static class Log4jLoggingLogFactory implements AbstractLogFactory {
69          public Log getLog(Class<?> clazz) {
70              return new Log4jImpl(clazz);
71          }
72      }
73  
74      public static void setLogFactory(AbstractLogFactory logFactory) {
75          LogFactory.logFactory = logFactory;
76      }
77  }