On Dec 24, 2007, at 4:42 AM, Eric Xin Zhang wrote:


Forgive me if similar question has been answered before. I searched the forum
but could not find exact answer.


My intention is to generate some system running report in text format
(something like the windows startup log for troubleshooting), and my idea is
to make use of log4j by wrapping Logger class into a new class, say
RunningReport.


I wrote codes as below:



public class RunningReport
{
   public RunningReport(File file) throws IOException
   {

       logger = Logger.getLogger(this.toString()); // Question 1)
// PropertiesUtil to get the pattern property from properties file
       layout = new
PatternLayout(PropertiesUtil.getProperty("report.pattern"));
       appender = null;

       FileOutputStream output = new FileOutputStream(file);
       appender = new WriterAppender(layout, output);

       logger.addAppender(appender);
       logger.setLevel(Level.DEBUG);
   }

   public void log(String message)
   {
       logger.debug(message);
   }
   // Question 2)
}




My questions are:

1) Apparently here I could not retrieve the Logger by given a static name in String, or a class. Each time when the RunningReport instantiated, a new Logger shall be retrieved. So I wrote the code like that. Not sure whether
the approach correct or not. I got some hints that for such case, it's
better to code my own Appender. If that's true, how shall I do?



The logger hierarchy allows you to arrange messages by topic and allows you to use an external configuration to decide where specific messages should go or whether they should be active at all. If you are using RunningReport.toString() as the logger name, you make it impractical to configure in an external configuration file.

You don't seem to be adding any value in your wrapper other than forcing an initial configuration. In general, it is desirable to not do explicit configuration in the code and allow an external configuration file so that users may enable, disable, or change configuration.

If you really don't want to use the log4j request dispatching logic, you could always create a LoggingEvent in your code and send it directly to the FileAppender bypassing the dispatching logic in logger.


2) Is there any method like flush() in Logger that I can call to make sure
all the messages are written into file?


No, but you can call WriterAppender.setImmediateFlush(true) so that every append operation flushes the writer.

Thanks in advance and with you all a Merry X'mas!


--
View this message in context: 
http://www.nabble.com/Wrapping-Logger-tp14486449p14486449.html
Sent from the Log4j - Users mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to