While ArgumentFormatters make
it easy to log any kind of object, what if we want to customize lo
messages based on which objects are specified? The best example
is logging a text message and an exception. This is exactly the type
of situation
SignatureFormatters
was designed for!
|
Example |
Before |
For example, this code:
SimpleLogger logger = new SimpleLogger();
logger.getListenerContainer().add( new ConsoleListener() ); // output to System.out w/o timestamp
logger.getArgumentContainer().add( new StringArgFormatter() ); // formats the string
logger.getArgumentContainer().add( new ThrowableArgFormatter() ); // formats the exception
try
{
throw new IllegalArgumentException( "Bad Argument" );
}
catch( IllegalArgumentException ex )
{
logger.error( "An error occurred!", ex );
}
Outputs:
(ERROR) (2 items in collection)
[ 0 ] An error occurred!
[ 1 ] Throwable - Type: java.lang.IllegalArgumentException; Message: Bad Argument
logahawk.swing.DemoFrame.main(DemoFrame.java:41)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
com.intellij.rt.execution.application.AppMain.main(AppMain.java:90)
|
After |
This displays all the information we want, but it would be nice if
Logahawk didn't interpret this as a list of two elements, and instead
formatted as if the message and exception were related.
See the difference when we add an StandardExceptionSigFormatter!
SimpleLogger logger = new SimpleLogger();
logger.getListenerContainer().add( new ConsoleListener() ); // output to System.out w/o timestamp
logger.getArgumentContainer().add( new StringArgFormatter() ); // formats the string
logger.getArgumentContainer().add( new ThrowableArgFormatter() ); // formats the exception
logger.getSignatureFormatter().add( new StandardExceptionSigFormatter() ); // !!!
try
{
throw new IllegalArgumentException( "Bad Argument" );
}
catch( IllegalArgumentException ex )
{
logger.error( "An error occurred!", ex );
}
Output:
(ERROR) An error occurred!
Throwable - Type: java.lang.IllegalArgumentException; Message: Bad Argument
logahawk.swing.DemoFrame.main(DemoFrame.java:41)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
com.intellij.rt.execution.application.AppMain.main(AppMain.java:90)
Much better!
(I ran these examples from IntelliJ, my IDE of choice. Your stack traces might vary.)
|