h1ghlevelb1ts

sed to the rescue (or how to migrate from java.util.logging to org.slf4j)

I got the task to migrate all our code - some 100 classes - from standard JDK logging to the logging facade framework slf4j. (I am not sure if there are any real benefits from such a migration but the deploying organization has decided that this is the way to go so the best approach i to just look happy and accept. They also claim that there may be performance issues with the way we log now. It sounds a bit far-fetched to me....) A fast analysis of the task made me conclude that I needed to replace:

  • the import of java.util.logging.Logger with org.slf4j.*
  • the line constructing the Logger instance to use the slf4j LoggerFactory instead
  • .fine, .finer and .finest with .debug (for some reason .debug is the finest level in the slf4j API)
  • .warning with .warn
  • .severe with .error
A tedious work to do by hand. Thankfully there is a nice little unix command called sed that together with find does the trick almost perfectly. Here is the script I used:
#/bin/ksh
for file in `find . -name '*.java'`
do
 cleartool co -c "Changing log framework thingie." $file
 sed -e 's/java.util.logging.Logger/org.slf4j.*/' \
     -e 's/= Logger.getLogger/= LoggerFactory.getLogger/' \
     -e 's/.fine(/.debug(/'  \
     -e 's/.finer(/.debug(/' \
     -e 's/.warning(/.warn(/' \
     -e 's/.severe(/.error(/' \
     $file > $file.tmp
 mv $file.tmp $file
done
As you can see I also added a line to check out the file from Clearcase. If you are using CVS, subversion or even git (as any developer would given a free choice....) there is no need.
 
A couple of files failed to compile after the migration. Curly braces disappeared at the end of some classes and in one case the logger was instantiated on 2 lines instead of one but overall it worked nicely.
 
This way of working comes rather natural to me but I gather that not all developers think of the command line as a helpful tool and thus this blog post.
 

Old comments

2009-09-16Hardy Ferentschik
Sweet :) What would life be without sed, awk, find and grep. Any developer should have these tools in his toolbox.
2009-09-17Ceki
This post has been removed by the author.
2009-09-17Ceki
Have you looked at the SLF4J migrator? It accomplishes what you describe, except for the fine/finer/finest to debug mapping.
2009-09-17Fredrik Rubensson
Seems like my 10 line script was a bit better than the migrator then! Sometimes a few lines of unix scripting is all you need. But it is of course good that there are tools since many developers don't have a clue about unix.