Forum Discussion

davidp_1's avatar
davidp_1
Occasional Contributor
10 years ago

Custom Logging of assert statements from Groovy script

I'd like to use the "assert" statement in Groovy and would like to put that nice output into a separate file. Right now I see that it goes into the error file (ready-api-errors.log), but I'd like the assertions to go into their own file. I know I can set up a custom logger, and specify that in a script for other types of log statements that I write myself. However, I want the output of the groovy assert statement to go into that custom log file. I'm sure I'm missing something really simply here...

 

Thanks!

    • davidp_1's avatar
      davidp_1
      Occasional Contributor

      Hi -- Yes, I'd seen that post, and that's where I learned about setting up the custom logger. What I was missing was pretty simple -- how to get groovy assert results into that file. I needed to put the assert into a try/catch, like this:

       

      import org.apache.log4j.Logger 
      def fileLogger = Logger.getLogger("ASSERTION.SCRIPT.LOGGER");
      
      def String expected = "Some Text"
      def String actual = "Some Unexpected Text"
      
      assertVals(actual, expected, fileLogger)
      
      def assertVals(String actual, String expected, Logger logger) {
      	if (expected != null) {
      		try {
      			assert expected == actual 
      		} 
      		catch(AssertionError e) {
      			logger.info(e.getMessage())
      		}
      	}
      }

      Two notes:

      • If you want the "power assert" formatting in the file, leave it as above. If you want a more standard version on a single line, add the optional ": 'This is the result'" part after the assert statement. Not sure why that is, but it works.
      • Because the "power assert formatting is sensitive, I turned off the formatting in the layout of the appender.
               <layout class="org.apache.log4j.PatternLayout">
                  <param name="ConversionPattern" value="%m%n"/>
              </layout>

      Of course, when you do that you don't get useful stuff like date/time. 

       

      Thanks,

       

      • nmrao's avatar
        nmrao
        Icon for Champion Level 2 rankChampion Level 2

        If you are looking for date and all you need provide the appropriate value in the configuration for ConversionPattern.

        You may try something like below

        %d{dd-MMM-yyyy HH:mm:ss,SSS} [%-8t] %-5p  %c{1}:%L %x - %m %n