Log4j VS other logging APIs

I need a logging API for my current application, and I was going to go with log4j. I just wanted to check first to make sure that there were no other more popular loggers, or logging APIs build directly into Java 1.5.
Thanks for any info,
John

Log4j has extensive use within the J2EE community, while java.util.logging is (relatively) new. If you're not sure you'll stick to one or the other, you could use a higher-level API like Apache's commons logging :
http://jakarta.apache.org/commons/logging/Then you could use whatever logging solution you choose and switch at a later time without impacting your program in a significant way.

Similar Messages

  • Is this logging code faster than using a standard logging API like log4J

    is this logging code faster than using a standard logging API like log4J or the logging API in java 1.4
    As you can see my needs are extremely simple. write some stuff to text file and write some stuff to dos window.
    I am thinking about using this with a multi threaded app. So all the threads ~ 200 will be using this simultaneously.
    * Tracer.class logs items according to the following criteria:
    * 2 = goes to text file Crawler_log.txt
    * 1 = goes to console window because it is higher priority.
    * @author Stephen
    * @version 1.0
    * @since June 2002
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.text.*;
    class Tracer{
    public static void log(int traceLevel, String message, Object value)
    if(traceLevel == 1){
    System.out.println(getLogFileDate(new Date()) +" >" + message+ " value = " + value.toString()););
    }else{
    pout.write(getLogFileDate(new Date()) +" >" + message + " value = " + value.toString());
    pout.flush();
    public static void log(int traceLevel, String message )
    if(traceLevel == 1){System.out.println(message);
    }else{
    pout.write(message ) ;
    pout.flush();
    //public static accessor method
    public static Tracer getTracerInstance()
    return tracerInstance;
    private static String getLogFileDate(Date d )
    String s = df.format(d);
    String s1= s.replace(',','-');
    String s2= s1.replace(' ','-');
    String s3= s2.replace(':','.');
    System.out.println("getLogFileDate() = " + s3 ) ;
    return s3;
    //private instance
    private Tracer(){
    System.out.println("Tracer constructor works");
    df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
    date = new java.util.Date();
    try{
    pout = new PrintWriter(new BufferedWriter(new FileWriter("Crawler_log"+getLogFileDate(new Date())+".txt", true)));
    pout.write("**************** New Log File Created "+ getLogFileDate(new Date()) +"****************");
    pout.flush();
    }catch (IOException e){
    System.out.println("**********THERE WAS A CRITICAL ERROR GETTING TRACER SINGLETON INITIALIZED. APPLICATION WILL STOP EXECUTION. ******* ");
    public static void main(String[] argz){
    System.out.println("main method starts ");
    Tracer tt = Tracer.getTracerInstance();
    System.out.println("main method successfully gets Tracer instance tt. "+ tt.toString());
    //the next method is where it fails - on pout.write() of log method. Why ?
    tt.log(1, "HIGH PRIORITY");
    System.out.println("main method ends ");
    //private static reference
    private static Tracer tracerInstance = new Tracer();
    private static Date date = null;
    private static PrintWriter pout = null;
    public static DateFormat df = null;
    }

    In general I'd guess that a small, custom thing will be faster than a large, generic thing with a lot of options. That is, unless the writer of the small program have done something stupid, og the writer of the large program have done something very smart.
    One problem with java in this respect is that it is next to impossible to judge exactly how much machine-level processing a single java statement takes. Things like JIT compilers makes it even harder.
    In the end, there is really only one way to find out: Test it.

  • Does the logging API provide  "Asynchronous File Handler", like log4j ?

    Hi,
    One more question about java.util.logging:
    Does sun provide a standard "Asynchronous File Handler", equivalent to log4j AsyncFileAppender ?
    The idea is, logging requests are placed into a queue, which is being consumed by a dedicated logging-IO thread.
    Thanks.

    it's a shame, really. the Logging API was blatantly inspired by Log4J, but it's just such a poor cousin in so many ways...

  • How come logging is so hard? - JDK1.4 Logging API

    Have a small project on hand. A standalone java program trigged by unix cron job and do some data cleaning. Need to implement a very simple logger. Tried to use JDK1.4 Logging API, here's my code:
    public class MyLogManager {
         public final static String NAME = "mylog";
         public final static String LOG_FILE_NAME = "C:/my.log";
         private static Logger logger;
         static {
              try {
                   logger = Logger.getLogger(NAME);
                   Handler fh = new FileHandler(LOG_FILE_NAME);
                   fh.setFormatter(new SimpleFormatter());
                   logger.addHandler(fh);
                   logger.setLevel(Level.ALL);
              } catch (Exception e) {
                   System.out.println("Unable to initialize logger: " + e.toString());
                   System.exit(1);
         public static Logger getLogger() {
              return logger;
    and use MyLogManager.getLogger().info("message") to log message.
    It works and my.log was generated with log message. However, the problem is everytime a new job (java myprogam ...) runs, it deletes the old log file and create a new one.
    I want the message to be appended by the end of old log file. What should I do? Any help?

    Use log4j (google for it - it's on http://jakarta.apache.org).
    If log4j.jar is in your classpath, the JDK 1.4 logging framework will use it automatically. Then all you have to do is to configure a log4j.properties file in your classpath to log wherever you want it to.
    And log4j is sorta-smart about multiple programs logging to the same file.

  • Log API: daily roling file appender?

    my task is to replace Log4J with the JDK 1.4 logging API. how can i configure the logging to have a FileHandler that does daily rolling (like Log4J DailyRollingFileAppender) and offer a a date pattern for the file name (like Log4J DatePattern)?
    the result should be that each day, a new log file is created with the old files having a datepattern in the file names.

    Well, i wrote my own now, that supports time rolling (day, week, month, year) and later additional rollings. here's a start:
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import java.util.logging.*;
    * File handler that supports different kind of rolling than java.util.logging.FileHandler.
    * Supported rolling methods are: by date (day).
    * <p>
    * Example of entries in the logging file (system property "java.util.logging.config.file"):
    * <p>
    <table align="center" bgcolor="#ddddff" border=1 cellpadding="10" cellspacing="0"><tr><td><pre>
    logging.RollingFileHandler.level = FINEST
    logging.RollingFileHandler.prefix = MyApp_
    logging.RollingFileHandler.dateFormat = yyyyMMdd
    logging.RollingFileHandler.suffix = .log
    logging.RollingFileHanlder.cycle=day
    logging.RollingFileHandler.formatter = java.util.logging.SimpleFormatter
    </pre></td></tr></table>
    <p>
    * @version $Revision:$ ($Date:$)
    * @author $Author:$
    public class RollingFileHandler extends StreamHandler {
        /** File prefix. */
        private static String prefix = null;
        /** Date format to use in file name. */
        private static String dateFormat = "yyyy-MM-dd"; //default
        /** File suffix. */
        private static String suffix = null;
        /** Time in milliseconds for the next cycle */
        private static long nextCycle = 0;
        /** Time cycle (for file roling) */
        private static String cycle = "day"; //default
         * Constructor.
        public RollingFileHandler() {
            super();
            LogManager manager = LogManager.getLogManager();
            String className = RollingFileHandler.class.getName();
            prefix = manager.getProperty(className + ".prefix");
            String dfs = manager.getProperty(className + ".dateFormat");
            suffix = manager.getProperty(className + ".suffix");
            String c = manager.getProperty(className + ".cycle");
            String formatter = manager.getProperty(className + ".formatter");
            if (dfs != null) {
                dateFormat = dfs;
            if (c != null) {
                if (c.equalsIgnoreCase("day") || c.equalsIgnoreCase("week") || c.equalsIgnoreCase("month") || c.equalsIgnoreCase("year")) {
                    cycle = c;
            if (formatter != null) {
                try {
                    setFormatter((Formatter) Class.forName(formatter).newInstance());
                } catch (Exception e) {
                    e.printStackTrace(System.err);
            openFile();
        }//RollingFileHandler()
          * Open existing or create new log file.
         private synchronized void openFile() {
            //create file name:
            String dateString = dateFormat; //default (to note error in file name)
            Date currentDate= new Date();
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.getDefault());
                dateString = sdf.format(currentDate);
            } catch (IllegalArgumentException iae) {
                /* ignore wrong date format */
            //compute next cycle:
            Date nextDate = null;
            GregorianCalendar gc = new GregorianCalendar();
            gc.setTime(currentDate);
            if (cycle.equalsIgnoreCase("week")) {
                gc.add(Calendar.WEEK_OF_YEAR, 1);
                nextDate = gc.getTime();
            } else if (cycle.equalsIgnoreCase("month")) {
                gc.add(Calendar.MONTH, 1);
                int month = gc.get(Calendar.MONTH);
                int year = gc.get(Calendar.YEAR);
                GregorianCalendar gc2 = new GregorianCalendar(year, month, 1);
                nextDate = gc2.getTime();
            } else if (cycle.equalsIgnoreCase("year")) {
                gc.add(Calendar.YEAR, 1);
                int year = gc.get(Calendar.YEAR);
                GregorianCalendar gc2 = new GregorianCalendar(year, 0, 1);
                nextDate = gc2.getTime();
            } else { //day by default
                gc.add(Calendar.DAY_OF_MONTH, 1);
                nextDate = gc.getTime();
            //to zero time:
            gc = new GregorianCalendar();
            gc.setTime(nextDate);
            gc.set(Calendar.HOUR, 0);
            gc.set(Calendar.HOUR_OF_DAY, 0);
            gc.set(Calendar.MINUTE, 0);
            gc.set(Calendar.SECOND, 0);
            gc.set(Calendar.MILLISECOND, 0);
            nextDate = gc.getTime();
            nextCycle = nextDate.getTime();
            //create new file:
            String fileName = prefix + dateString + suffix;
            File file = new File(fileName);
            //create file:
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException ioe) {
                    ioe.printStackTrace(System.err);
            //set log file as OutputStream:
            try {
                FileOutputStream fos = new FileOutputStream(file, true);
                setOutputStream(fos);
            } catch (FileNotFoundException fnfe) {
                reportError(null, fnfe, ErrorManager.OPEN_FAILURE);
                fnfe.printStackTrace(System.err);
                setOutputStream(System.out); //fallback stream
        }//openFile()
         * Overwrites super.
        public synchronized void publish(LogRecord record) {
            if (!isLoggable(record)) {
                return;
            super.publish(record);
            flush();
            //check if we need to rotate
            if (System.currentTimeMillis() >= nextCycle) { //next cycle?
                role();
        }//publish()
          * Role file. Close current file and possibly create new file.
         final private synchronized void role() {
            Level oldLevel = getLevel();
            setLevel(Level.OFF);
            super.close();
            openFile();
            setLevel(oldLevel);
        }//rotate()
    }//RollingFileHandler

  • Logging api hangs

    Im starting a java application from an applet calling Runtime.getRuntime().exec("java bla bla bla")
    Worked fine until I implemented Java 1.4 logging api. Now the application hangs after writing a few info lines to a FileHandler log. It's clearly the logger that hangs because if I set log level = OFF the the program runs just fine.
    Has anyone seen anything similar?
    * To make it harder to debug, the problem only occurs when starting the application from an applet.

    That might happen that spawn process generates lots of output.
    Runtime.getRuntime().exec() returns object of type java.lange.Process. That object provide access to the stdout and stderror of the newly created process. If those streams are not cleaned properly then process will hang as soon as OS buffers of those stdout and stderr streams get full.
    One way to work around it just read output from the process and throw it away. You can try using something like this:
    package com.xxx;
    import java.io.InputStream;
    public class ProcessOutputWaster {
        public ProcessOutputWaster(Process process)
            throws Exception {
            createWorker(process.getErrorStream()).start();
            createWorker(process.getInputStream()).start();
        protected Worker createWorker(InputStream is) {
            return new Worker(is);
        protected static class Worker
                  extends Thread {
            private InputStream inputStream_;
            public Worker(InputStream inputStream) {
                inputStream_ = inputStream;
            public void run() {
                if (getInputStream() != null) {
                    try {
                        byte[] buffer = new byte[1024];
                        int read;
                        while(true) {
                            read = inputStream_.read(buffer);
                            if (read < 0)
                               break;
                    catch(Exception ex) {
                        Handle the error some how. E.g. show the error box.
    Process process = Runtime.getRuntime().exec(strCommand);
    ProcessOutputWaster outputWaster = new ProcessOutputWaster(process);

  • Practical use of Java Logging API

    There was a recent technical tip about the Java Logging API, but after reading it I still don't understand how to use it in a real situation.
    Can anyone help me with this with a practical example?
    At the moment I have try-catch clauses that catch exceptions and print a message in a System.err log that I can consult if there's a specific problem.
    How should I be using the Logging API? I feel sure that it can help me, but can't see how.
    Thanks for any practical information.

    What if you don't want to write to system.err anymore? What if you need to write something to the windows event log? What if system.err is irrelevant (nt service), ...
    Btw, lots of examples on the JDK1.4 logging api:
    http://www.esus.com/docs/GetIndexPage.jsp?uid=265

  • How to set NC Log API

    Hi all,
    I want to use the following NC log API,but I don't know how to initialize the interface's java object and set the parameter "ApplicationVO".
    Interface LogNCApplicationInterface
    Method ApplicationVO addNDone(ApplicationVO applicationvo)
    Please help me.Thank you!
    Qiang Liu

    if you just need to log an NC the minimum fields you need to set are the following:
    CreateNCRequest ncRequest = new CreateNCRequest();
    ncRequest.setActivity("NC500"); // activity where NC is logged - can be any name
    ncRequest.setSfcRef(new SFCBOHandle(site, sfcParent).toString());// the SFC for which you are reporting an NC
    // ncRequest.setValidateNCCodeOperation(true); // no need to set it, it's true by default
    // nc code reference for nc code that is reported
    // nc code must exist in the system
    ncRequest.setNcCodeRef(new NCCodeBOHandle(site,"NCCODE").toString());
    // required custom fields must be set
    CreateNCResponse ncResponse = ncPSI.createNC(ncRequest);

  • Setting Logging API config file

    Hi,
    Is there a way I can set the Logging API's config file (java.util.logging.config.file) from within my program? I have tried using System.setProperty but it doesn't seem to work. The only way I seem to be able to set the property is with -D on the command line.
    Thanks
    Rob

    Is there a way I can set the Logging API's config file (java.util.logging.config.file) from within my program? I have tried using System.setProperty but it doesn't seem to work. The only way I seem to be able to set the property is with -D on the command line.Read the Logging Overview Dokumentation
    anyway
    InputStream inputStream = new FileInputStream("logging.properties");
    LogManager.getLogManager().readConfiguration(inputStream);
    ...

  • Logging API AdapterFramework 3.0

    Hello,
    i still wonder why it was necessary to provide an own API for Logging and Tracing inside the Adapter Framework.
    The Web AS Logging API does the same.
    Developing an JCA Adapter that can be used inside the XI Adapter Framework and as a Basic JCA 1.0 Adapter in the Web AS, theres's need to provide support for both APIs.
    Has anyone an idea to solve this problem?

    There is a lot of logging to the console with 2.3.0 RC1 when I am doing
    any trips to the datastore, is it possible to switch this off? I am
    using Kodo.rar in Jboss 3.0.0Remove the 'com.solarmetric.kodo.Logger' property from your properties file. You can also remove it from the Properties instance you use to construct the PersistenceManagerFactory. If you'd like to log to a file instead, change the property to the name of a file to log to.

  • Forum help for Logging api

    I need help with logging api. Which developer forum do I have to use for the same. Thanks.

    Have you got the SAP Wrapper for logging API? if you got, can you give it to me:)

  • Customize Java logging API

    Want to customize java.util.logging api, like write message to message queue, xml file, etc. Would you guys give me some useful suggestion or resource or link? Thanks.

    Just write a sub-class of Handler such as this:
    public class JMSHandler extends Handler {
    }Look into the JDK source code such as MemoryHandler and StreamHandler on how to implement it.

  • Jdk logging api

    iam using jdk logging api. I've a scenario,
    where there are two subclasses for a parent one.
    is it suffice to use Logger.getLogger("packagename.superclass");
    in the parent class, for all the subclasses to use the same logging medium.
    Thanks

    What happened when you tried that?

  • [svn:osmf:] 14984: Updating to work with the latest logging API changes.

    Revision: 14984
    Revision: 14984
    Author:   [email protected]
    Date:     2010-03-24 07:23:14 -0700 (Wed, 24 Mar 2010)
    Log Message:
    Updating to work with the latest logging API changes.
    Modified Paths:
        osmf/trunk/apps/samples/framework/OSMFPlayer/src/DebuggerLogger.as

    Revision: 14984
    Revision: 14984
    Author:   [email protected]
    Date:     2010-03-24 07:23:14 -0700 (Wed, 24 Mar 2010)
    Log Message:
    Updating to work with the latest logging API changes.
    Modified Paths:
        osmf/trunk/apps/samples/framework/OSMFPlayer/src/DebuggerLogger.as

  • Log4j Vs commons-logging

    Can any one get me the difference between Log4j and commons-logging.
    Or, if both are same which one compliments the other.
    Thankls
    - Java Buddy.

    Can any one get me the difference between Log4j and
    commons-logging. Both are logging mechanisms.
    Or, if both are same which one compliments the
    other.Commons logging can be configured to internally use Log4J.
    http://jakarta.apache.org/commons/logging/guide.html#Configuration

Maybe you are looking for

  • Is there a way to find the serial number in these files so that I can reinstall the full version?

    I had to restore from backup to a new hard drive, and only have part of my Adobe Photoshop installation. Is there a way to find the serial number in these files so that I can reinstall the full version?  I have only part of the documentation so this

  • Staging area for inserts only?

    If our DW will only over contain inserts, do we require a staging area?

  • Blue screen on DVI

    have a problem today with a blue screen on dvi connection using original mac mini and syntax olevia 30". was fiddling around in displays earlier and saw a higher res display that syntax manual said dvi could handle, so said "hey, wonder if that'd wor

  • ApexLib_TabForm

    Hi, I need to edit a row on a grid page, when the row is selected for that in a checkbox control, I use the next code BEGIN FOR ii IN 1 .. ApexLib_TabForm.getRowCount LOOP IF ApexLib_TabForm.hasRowChanged(ii, TRUE) THEN IF ApexLib_TabForm.isRowSelect

  • Share Error Quick Time Failure -50. Anyone know what's going on?

    I'm trying to transcode a five minute project that's fairly involved - multiple audio and video channels, graphics etc. When I try to send it out of the Share option in Final Cut 7 to either Apple TV or Mobile Me or YouTube, I keep getting the same t