tags:

views:

54

answers:

2

Hello,

I am writing a command line tool that performs a number of tests to our servers and reports an output to screen.

I am currently using log4j to print to screen and to a log file.

However, I was wondering if there was a better technique to manage all the printing from one class instead of having the "print" commands scattered all over my code.

e.g.

logger.info("Connecting to environment: " + envName);

if (cmd.hasOption(OPTION_CHECK_PRIMARY)) {
    //print primary leg
    String primaryLegName = env.getPrimaryLeg().getLegName();
    String message = "is primary";

    logger.info(String.format("%s : %-4s %s", envName, primaryLegName, message));
}

This is an example of the output that is now scattered across all my code.

Would it be best to have a Formatter class that handles all the printing?

What is the best approach to create it?

What do you think about something like:

Formatter pf = new PlainFormatter();
...
pf.printEnvironment(envName);

if (cmd.hasOption(OPTION_CHECK_PRIMARY)) {
    //print primary leg
    String primaryLegName = env.getPrimaryLeg().getLegName();
    pf.printPrimary(envName, primaryLegName); 
}
A: 

Have you tried using log4j.properties to format the text. I think if you are trying to format uniquely for each class, then this is still possible using log4j.properties.

Here is a simple example of log4j.properties

log4j.rootLogger=INFO, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout

You can use Pattern in properties like so:

log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
Amir Raminfar
Hi Amir, I am using log4j at the moment, so I am doing exactly as you say. However, I do not want to be printing from different part of the code, but I would rather have a single/external class that handles the printing. This way if I want to change the way I display the output, I do not have to go and look for the print statements in all my classes.
Alessandro
What do you plan to change in the future? Isn't formatting and logging level controlled via properties file anyway? Would there be a reason to abstract out just a one line function call?
Amir Raminfar
A: 

log4j has appenders to redirect log messages to different locations. quote" Multiple appenders exist for the console, files, GUI components, remote socket servers, JMS, NT Event Loggers, and remote UNIX Syslog daemons "unquote

kuriouscoder