Hi all,

I am working I18N of log4j. So when i enter unicode data it should
display in right format in Output file.
In this example i am using UI.java file to take multibyte data from
Swing application & passing to LOGGER,
but in the Output file it is displaying as junk charcter.
I m sending all 4 files contain at the end.

Please help me in this matter ASAP.

Thank in advance.



1 )SampleLogger.java file

import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.apache.log4j.Level;
import org.apache.log4j.*;
import org.apache.log4j.xml.DOMConfigurator;

import java.io.FileWriter;
import java.io.IOException;


/**
 * This class contains methods for performing logging.
 * A call to these methods will make a log entry as per the settings in
 * Log4j.xml file. This file determines the log level at which a log
 * message will be written to a log file.
 * The class provide two methods "writeLogUsingPriorityObject" and
"writeLog". These two methods
 * are alternative methods, any one method can be used for Logging.
 *
 * The two methods in turn give call to methods of logger class.
 * log() method of Logger class is a generic method for logging as
opposed to specific
 * methods like debug(), info(), warn(), error() and fatal()
 *
 *
 */
public class SampleLogger
{
    Logger simpleLog;

    //Path for Config File
    public static final String CONFIG_FILE
="D:\\Java\\LOG4J\\Log4JConfig.xml";

    //Path for Output Log File
   public static final String OUTPUT_FILE =
"D:\\Java\\LOG4J\\Output.log";

    public void init()
    {
        try
        {
 
           /*Read the Configuration file if it exists. By calling
            DOMConfigurator.configureAndWatch (CONFIG_FILE) a thread
            will be created that will periodically check if the file is
created
            or modified. The check is performed every 60 secs(default,
can be changed)
            If a change or file creation is detected then CONFIG_FILE is
read to
            configure log4j.*/

            DOMConfigurator.configureAndWatch (CONFIG_FILE);

            /*Retrieve a logger by name */
            simpleLog = Logger.getLogger("categorylnnz");
     
        if ( simpleLog != null )
  {
   try
   {
   
      Appender obja=simpleLog.getAppender("LNNZ_4J");
    // System.out.println (simpleLog.getName());
   //  System.out.println (simpleLog.getAppender("LNNZ_4J"));
     ((WriterAppender)obja).setEncoding("UTF-8");
   //  System.out.println (simpleLog.getAppender("LNNZ_4J"));
     //   System.out.println
(((WriterAppender)(simpleLog.getAppender("LNNZ_4J"))).getEncoding());


   }
   catch (Exception e)
   {
    simpleLog.debug("No appender found");
   }
  }

               
           
            /* Additivity is a field of Logger class, which is set to
true by default,
            that is children inherit the appenders of their ancestors by
default.*/
            simpleLog.setAdditivity(true);

        }catch(Exception e)
        {
            System.out.println ( "Exception  "+ e );
        }
    }


    /**
     *  This method takes in two parameters. The first parameter is the
Log message
     *  to be written in to the log file. The second parameter is the
Level of
     *  log message. This method classify the level of the logging and
     *  give call to appropriate methods of Logger class.
     *
     * @param Log String describing the log message
     * @param LogLevel An integer with appropriate Log Level(DEBUG,
INFO, WARN, ERROR)
     */
    public void writeLog(String Log, int LogLevel )
    {
  //classifying the loglevel and giving call to appropriate function of
        //Logger class.
        if (Level.DEBUG_INT == LogLevel)
  {
   simpleLog.debug (Log);
  }
  else if (Level.INFO_INT == LogLevel)
  {
   simpleLog.info (Log);
  }
        else if (Level.WARN_INT == LogLevel)
        {
            simpleLog.warn(Log);
        }
        else if (Level.ERROR_INT == LogLevel)
        {
            simpleLog.error (Log);
        }
        else if (Level.FATAL_INT == LogLevel)
        {
            simpleLog.fatal(Log);
        }
    }

    /**
     * This is an alternative method for logging.
     * This method creates a Priority Object with priority value equal
to
     * the input value(LogLevel).
     * The priority object is then passed as a parameter to log function
of logger
     * class, which in turn writes the log with appropriate priority.
     *
     * @param Log String describing the Log message.
     * @param LogLevel An integer with appropriate Log Level(DEBUG,
INFO, WARN, ERROR)
     */
    public void writeLogUsingPriorityObject(String Log, int LogLevel)
    {
        //Setting the priority
        Priority p = Priority.toPriority(LogLevel);
        /*Writing the log using the log() method of Logger class*/
        simpleLog.log(p, Log);
    }
}

2 ) Log4JConfig.xml


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>

 <appender name="LNNZ_4J"
class="org.apache.log4j.DailyRollingFileAppender">
            <param name="File" value="D:\\Java\\LOG4J\\Output.log" />
            <param name="Append" value="true" />     
   <param name="DatePattern" value="'.'yyyy-MM-dd"/>
            <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern" value="%x %p %d{dd MMM yyyy HH:mm:ss}
- %m%n"/>
            </layout>
 </appender>


 <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
  <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern"
                            value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
  </layout>
 </appender>

 <category name="categorylnnz">
  <priority value="info"/>
  <appender-ref ref="LNNZ_4J"/>
 </category>

 <root>
    <priority value ="debug" />
       <appender-ref ref="STDOUT" />
 </root>

</log4j:configuration>

3 ) UI.java



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
import org.apache.log4j.Level;
 
public class UI extends JPanel implements ActionListener
{
 protected JTextField textFieldReq;
 protected JTextField textFieldRes;
 protected String username;
 protected String password;
 private JButton btn;

 public UI()
 {
  super(new GridBagLayout());

  textFieldReq = new JTextField(20);
  textFieldRes = new JTextField(20);
  btn = new JButton("Write Text & prees");
  btn.addActionListener(this);

  this.add(textFieldReq);
  this.add(textFieldRes);
  this.add(btn);
 }

 public void actionPerformed(ActionEvent evt)
 {
  username = textFieldReq.getText();
  password = textFieldRes.getText();
 
  SampleLogger objSampleLogger = new SampleLogger();
        objSampleLogger.init();
      
       // Taking username & password from UI & send it to LOGGER
       objSampleLogger.writeLog("Username::"+username, Level.ERROR_INT);
       objSampleLogger.writeLog("Password::"+password, Level.ERROR_INT);
       objSampleLogger.writeLog("This is End of Function :: Fatal
Message using writeLog()", Level.FATAL_INT);
 }

 private static  void createAndShowGUI()
 {
  JFrame frame = new JFrame("TEXT DEMO");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  JComponent newContentPane = new UI();
  newContentPane.setOpaque(true); //content panes must be opaque
  frame.setContentPane(newContentPane);

  frame.pack();
  frame.setVisible(true);
 }

 public static void main(String[] args)
 {
  javax.swing.SwingUtilities.invokeLater(new Runnable()
  {
   public void run()
   {
    createAndShowGUI();
    
   }
  });
 
 }
}


4 )  Outpu.log file

 ERROR 27 Jul 2006 17:55:18 - Username::??
 ERROR 27 Jul 2006 17:55:18 - Password::???
 FATAL 27 Jul 2006 17:55:18 - This is End of Function :: Fatal Message
using writeLog()
 ERROR 27 Jul 2006 17:58:40 - Username::sdfs
 ERROR 27 Jul 2006 17:58:40 - Password::sdf
 FATAL 27 Jul 2006 17:58:40 - This is End of Function :: Fatal Message
using writeLog()




warm regards,
Hardik Patel





**************** CAUTION - Disclaimer *****************
This e-mail contains PRIVILEGED AND CONFIDENTIAL INFORMATION intended solely 
for the use of the addressee(s). If you are not the intended recipient, please 
notify the sender by e-mail and delete the original message. Further, you are 
not to copy, disclose, or distribute this e-mail or its contents to any other 
person and any such actions are unlawful. This e-mail may contain viruses. 
Infosys has taken every reasonable precaution to minimize this risk, but is not 
liable for any damage you may sustain as a result of any virus in this e-mail. 
You should carry out your own virus checks before opening the e-mail or 
attachment. Infosys reserves the right to monitor and review the content of all 
messages sent to or from this e-mail address. Messages sent to or from this 
e-mail address may be stored on the Infosys e-mail system.
***INFOSYS******** End of Disclaimer ********INFOSYS***

Reply via email to