You are viewing a plain text version of this content. The canonical link for it is here.
Posted to log4j-user@logging.apache.org by Hardik Amarshibhai Patel <Ha...@infosys.com> on 2006/07/27 16:09:59 UTC

unicode support for log4j

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***

Re: unicode support for log4j

Posted by Curt Arnold <ca...@apache.org>.
On Jul 27, 2006, at 9:09 AM, Hardik Amarshibhai Patel wrote:

>
> 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.
>
....

> 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


I strongly suspect that the problem is either:

a) your default encoding is ISO-8859-1 (aka Latin 1 or Cp1252 on  
Windows) and the characters that you are emitted can not be  
represented in that encoding.
b) the file is being correctly written in UTF-8 and your editor  
assumes that it is in the default encoding and displays it incorrectly.

My first suggestion would be to explicitly set the encoding to  
"UTF-16" (which can be done in the configuration file) and open it  
with a compatible editor (for example, WordPad on Windows).  It is  
far less likely that there would be an encoding mismatch with a 2- 
byte encoding since the only commonly used encodings are the little  
endian and big endian varieties of UTF-16.

If that works (which it should) then set the encoding to "UTF-8" and  
use an editor that allows you to specify the encoding in use when the  
file is open (for example, later versions of Visual Studio or Kate).

If you are using an earlier version of log4j, please check if the  
problem still exists on the latest release or if possible the SVN  
version of the code.

If you still have problems, then please include the following  
information on your follow up message:

version of log4j
platform
editor/viewer used to display the file
code points of the expected characters
A hex dump of the generated file

The log4j unit tests have several tests to check the correct handling  
of encoding issues.  If you are able to run the unit test, please  
report if those tests fail.

To test your editor, open http://svn.apache.org/repos/asf/logging/ 
log4j/trunk/tests/witness/encoding/ in a browser and download  
UTF-8.log and UTF-16.log.  The files should have identical content  
displayed if you specify UTF-8 as the encoding for your editor.  The  
second line in the file should contain a superscript one and the  
third should a latin A, one character each from Arabic, Armenian,  
Begali, CJK and Cyrillic.  The last two are similar in shape to a T  
and E.  Likely not all will display due to missing fonts.



---------------------------------------------------------------------
To unsubscribe, e-mail: log4j-user-unsubscribe@logging.apache.org
For additional commands, e-mail: log4j-user-help@logging.apache.org