Grails Tip: Colored output
I really enjoy coding in Grails. When working with dynamic languages, there is always a bit more uncertainty to what the type of particular variable is – especially when calling code that someone else has written. Now, you can always just fire up the debugger to find out but often times it is overkill. Groovy has great support for finding out all about your object using dump(), inspect(), and toString() usually returns something useful from a GDK class. Usually a quick println is just the right thing for me to figure out what is going on, and then I remove the statement.
The problem with a quick println is that it is often difficult to quickly differentiate your log lines from that of Grails or Hibernate. Of course you can turn those log levels off, but always like to see the SQL Hibernate is generating during development. In order to make my logging stand out, I have started adding this to BootStrap.groovy:
1: def init = { servletContext ->
2: ...
3: Object.metaClass.printlnRed = { s ->
4: def ansi = new Ansi(Ansi.Attribute.BRIGHT, Ansi.Color.RED, Ansi.Color.BLACK);
5: ansi.outln(s);
6: }
7: ...
8: }
This will allow me to call “printlnRed ‘Some String’ from any Groovy object in my Grails application. The Ansi class comes from the LGPL licensed jibs library. Of course you will want to find out what colors work the best for you. Don’t forget to remove your println’s – you don’t want to clutter up your code for others. If it is something worth keeping in the application, use Log4J instead. You can still get colors by configuring your appenders to use Ansi colors as well – there are numerous examples of how to do this including one in Ant. FYI, I doubt this works in Windows.