Advertisement
Guest User

Untitled

a guest
Oct 28th, 2010
699
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 2.17 KB | None | 0 0
  1. import org.apache.log4j.LogManager
  2. import org.apache.log4j.PropertyConfigurator
  3.  
  4. /**
  5.  * This class will inject Log4j logger to your classes during integration test
  6.  * Please put a log4j_test.properties file with your test config in src/java
  7.  * directory or change the file loader to what suits you best.
  8.  */
  9. class TestLoggerLoader {
  10.     /**
  11.      * Default list of classes which will have logging injected
  12.      * Can be externalised if needed
  13.      */
  14.     private static final List<String> classes = [
  15.             "com.example.loggingTest.SrcTest",
  16.             "grailsloggingtests.Test",
  17.             "grailsloggingtests.TestController",
  18.             "grailsloggingtests.TestService"
  19.     ]
  20.  
  21.     /**
  22.      * Inject logging for single class
  23.      * @param fullClassName i.e. com.example.myProject.MyClass
  24.      */
  25.     public static void addLogging(String fullClassName) {
  26.         List<String> classList = [fullClassName]
  27.         loadLogging(classList)
  28.     }
  29.  
  30.     /**
  31.      * Inject logging for classes defined in 'classes' list
  32.      */
  33.     public static void addLogging() {
  34.         loadLogging(classes)
  35.     }
  36.  
  37.     /**
  38.      * Inject logging for a list of classes
  39.      * @param newClasses - List<String> of full class names
  40.      */
  41.     public static void addLogging(List<String> newClasses) {
  42.         loadLogging(newClasses)
  43.     }
  44.  
  45.     private static void loadLogging(List<String> classes) {
  46.         Properties props = new Properties();
  47.         try {
  48.             InputStream configStream = Thread.currentThread().contextClassLoader.getResourceAsStream("log4j_test.properties")
  49.             props.load(configStream)
  50.             configStream.close()
  51.  
  52.  
  53.             LogManager.resetConfiguration();
  54.             PropertyConfigurator.configure(props);
  55.  
  56.             for (className in classes) {
  57.                 def clazz = Class.forName(className, true, Thread.currentThread().contextClassLoader).newInstance()
  58.                 def logger = LogManager.getLogger(clazz.class.simpleName)
  59.                 clazz.class.metaClass.getLog << {-> logger}
  60.             }
  61.         } catch (Exception e) {
  62.             System.out.println("Error: Cannot inject logging");
  63.         }
  64.  
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement