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

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.

  • Problem with java logging API

    Hi there
    It`s the first time I`m using (I have to use) the standard java logging API.
    My need is to integrate it in an existing web-application based on struts.
    So my first step was to include the following code into an Struts Action-class:
    FileHandler file = new FileHandler("/pathToLogFile/myLogFile.log",true);
    file.setFormatter(new SimpleFormatter());
    logger.info("create info");
    By intention is to have exactly one log-file for the whole application, but indeed I'm getting multiple log-files, even for each request of one and the same Action/Servlet class, like
    myLogFile.log
    myLogFile.log.1
    myLogFile.log.2
    myLogFile.log.3
    Why does using append=true not work in the constructor of "FileHandler"
    Do I have to close the FileHandler each time I've used it?
    Is this a known issue?
    Thanks for any responds!

    @ Stone.li
    First, thanks for your answer.
    perhaps my question was quite confusing .... but my need is just
    to establish the logging API in an existing Web-Application and to have exactly one log-file for the whole application. This means I would have to provide in each servlet a FileHandler referencing to the log-file. I thought it would be part of the job of the logging API to synchronise this file access.

  • Java logging API (1.4) -- where's the file?

    Where on God's green earth does the log file get written to?
    I am doing some very simple code:
    import java.util.logging.*;
    public class SimpleLogging {
       static Logger jcfeLog = Logger.getLogger("test1");
       static Logger sampleLog = Logger.getLogger("test2");
       public static void main(String [] args)
          jcfeLog.warning("sample warning");
          sampleLog.log(Level.INFO, "sample info entry");
          byte[] moreInfo = new byte[10];
          //fill moreInfo with some binary info
          jcfeLog.log(Level.FINEST, "Some obscure event", new Object[]{moreInfo});
    } doesn't get much simpler, plus I am using the default properties file. I get the console output but simply cannot find the log file anywhere on my system. Just for kicks, here is the config entry for the file:
    java.util.logging.FileHandler.pattern =%t/java%u.logmy understanding is that it should go to the temp directory?
    also, why aren't the specs for the config file listed anywhere, all these %t, %u, etc.....????

    The FileHandler API gives the meaning for the % symbols.
    http://java.sun.com/j2se/1.4/docs/api/java/util/logging/FileHandler.html
    Your pattern indicates that the file should be put in the system's temp directory, with the file name java###.log.
    Maybe you should try calling the addHandler method on your Loggers, and add a FileHandler to write the messages to that file.

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

  • How to use the java native api

    i am new to the java native api, can anyone tell me how to use it in order for me to use the c++ file in the java file?please explain it if possible, thanks

    Try this out to learn the basics :
    http://java.sun.com/docs/books/tutorial/native1.1/index.html
    You can't go wrong from there.

  • Practical use for clickthru log

    Regarding the clickthru log (populated by the htmldb_util.count_click or Z procedure)...
    What is a practical use of this feature? Other than a "Huh, that many, eh? Nice" by glancing at it from the Admin pages.
    One thing I thought of was "self-destructing" download links where the link is rendered conditionally by querying the WWV_FLOW_CLICKTHRU_LOG view and checking the count(*) for that category.
    So, I decide that I want to allow this download to happen only, say, 100 times and then disable the link and put up a message "Sorry, maximum number of downloads exceeded" or something like that.
    Has anyone made any other use of this feature in their applications?
    Thanks

    Vikas,
    At CASEtech, we are using the clickthru log for 3 different activities within our product offering.
    1. We have on all the web sites we create for clients a footer link:
    "Site Design by CASEtech Inc. ©2004 All rights reserved." with a clickthru to track how many of our customer's customers are coming to our web site.
    2. We have a customer who has rotating advertising in their header, with an opportunity to click for more information. Our client wants to know how many times this advertising link is clicked for each of its "sponsors"
    3. We include the clickthu on images sent in emails from our Oolaroo - Oracle HTML DB applications as a way of tracking emails read.
    I. Michael Snyder
    Vice President, CASEtech, Inc.
    www.casetech.net
    President, MAOP
    www.maop.org
    Atlantic Oracle Training Conference
    Leveraging Your Oracle Investment
    December 8 - 9, 2005
    George Washington University
    Cafritz Conference Center
    Washington, DC

  • Problem getting calendar event with recurring using EWS Java client API 1.2

    I am using EWS 1.2 Java client API for getting calendar events. I am able to get Recurring information of the event which is created through API's 
    appointment.save(), but not able to get recurring information of the event created in OWA interface, I get following error during the bind:
    ===================================
    Exception: Connection not established
    microsoft.exchange.webservices.data.EWSHttpException: Connection not established
    at microsoft.exchange.webservices.data.HttpClientWebRequest.throwIfConnIsNull(HttpClientWebRequest.java:394)
    at microsoft.exchange.webservices.data.HttpClientWebRequest.getResponseHeaders(HttpClientWebRequest.java:280)
    at microsoft.exchange.webservices.data.ExchangeServiceBase.processHttpResponseHeaders(ExchangeServiceBase.java:1045)
    at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(SimpleServiceRequestBase.java:58)
    at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(MultiResponseServiceRequest.java:144)
    at microsoft.exchange.webservices.data.ExchangeService.internalBindToItems(ExchangeService.java:1364)
    at microsoft.exchange.webservices.data.ExchangeService.bindToItem(ExchangeService.java:1407)
    at microsoft.exchange.webservices.data.ExchangeService.bindToItem(ExchangeService.java:1430)
    at microsoft.exchange.webservices.data.Appointment.bind(Appointment.java:70)
    at microsoft.exchange.webservices.data.Appointment.bindToRecurringMaster(Appointment.java:176)
    at microsoft.exchange.webservices.data.Appointment.bindToRecurringMaster(Appointment.java:152)
    ============================
    This happens if I use: Appointment.bindToRecurringMaster or Item.bind(service, id, appointmentProps) or findAppointments(). 
    Works fine for events which doesn't have recurring. Only issue with events containing recurrence created through OWA. These are the propertySet:
    new PropertySet(BasePropertySet.IdOnly,
                                    ItemSchema.Subject,
                                    AppointmentSchema.AppointmentType,
                                    AppointmentSchema.DeletedOccurrences,
                                    AppointmentSchema.FirstOccurrence,
                                    AppointmentSchema.LastOccurrence,
                                    AppointmentSchema.IsRecurring,
                                    AppointmentSchema.Location,
                                    AppointmentSchema.ModifiedOccurrences,
                                    AppointmentSchema.OriginalStart,
                                    AppointmentSchema.Recurrence,
                                    AppointmentSchema.Start,
                                    AppointmentSchema.End);
    If I remove Recurrence it gives the response. 
    Thanks.

    I am using EWS 1.2 Java client API for getting calendar events. I am able to get Recurring information of the event which is created through API's 
    appointment.save(), but not able to get recurring information of the event created in OWA interface, I get following error during the bind:
    ===================================
    Exception: Connection not established
    microsoft.exchange.webservices.data.EWSHttpException: Connection not established
    at microsoft.exchange.webservices.data.HttpClientWebRequest.throwIfConnIsNull(HttpClientWebRequest.java:394)
    at microsoft.exchange.webservices.data.HttpClientWebRequest.getResponseHeaders(HttpClientWebRequest.java:280)
    at microsoft.exchange.webservices.data.ExchangeServiceBase.processHttpResponseHeaders(ExchangeServiceBase.java:1045)
    at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(SimpleServiceRequestBase.java:58)
    at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(MultiResponseServiceRequest.java:144)
    at microsoft.exchange.webservices.data.ExchangeService.internalBindToItems(ExchangeService.java:1364)
    at microsoft.exchange.webservices.data.ExchangeService.bindToItem(ExchangeService.java:1407)
    at microsoft.exchange.webservices.data.ExchangeService.bindToItem(ExchangeService.java:1430)
    at microsoft.exchange.webservices.data.Appointment.bind(Appointment.java:70)
    at microsoft.exchange.webservices.data.Appointment.bindToRecurringMaster(Appointment.java:176)
    at microsoft.exchange.webservices.data.Appointment.bindToRecurringMaster(Appointment.java:152)
    ============================
    This happens if I use: Appointment.bindToRecurringMaster or Item.bind(service, id, appointmentProps) or findAppointments(). 
    Works fine for events which doesn't have recurring. Only issue with events containing recurrence created through OWA. These are the propertySet:
    new PropertySet(BasePropertySet.IdOnly,
                                    ItemSchema.Subject,
                                    AppointmentSchema.AppointmentType,
                                    AppointmentSchema.DeletedOccurrences,
                                    AppointmentSchema.FirstOccurrence,
                                    AppointmentSchema.LastOccurrence,
                                    AppointmentSchema.IsRecurring,
                                    AppointmentSchema.Location,
                                    AppointmentSchema.ModifiedOccurrences,
                                    AppointmentSchema.OriginalStart,
                                    AppointmentSchema.Recurrence,
                                    AppointmentSchema.Start,
                                    AppointmentSchema.End);
    If I remove Recurrence it gives the response. 
    Thanks.
    I am also facing the same problem.. If anyone can help, it would be helpful. I can see the response xml has the data, but while parsing the xml the error is generated in getResponseCode() in HttpClientWebRequest

  • Practicable uses of Java?

    Hi,
    I'm extremely new to Java, but do have some deep programming knowledge of PHP. Anyway, I'm quite interested in Java and everything... it can seemingly do everything and anything you want it to do, from powering an entire megawebsite, to a simple class. I was just wondering what practicable uses Java has though? Do you only write programs and then execute them in your cmd window? I imagine not, but where else do you use Java? How exactly does Java play in to the "big picture" of things?
    Hope this makes sense... if you could... give me examples of programs and websites built entirely with Java.
    Just want to know what kind of things you can make with it... besides stuff in your cmd window. :P

    Hope this makes sense... if you could... give me examples of programs and websites built entirely with Java.
    This very site! :^)
    There is a difference between Java the language and Java Enterprise Edition (J2EE or JEE 5). The latter are generally used for web site creation. There are a number of tutorials on this site. Generally, Java has seemed to find its most successful implementations as middleware, integrating various other systems and servicing a number of clients (of which the web is probably the most popular). Hope that helps.
    - Saish

  • Want to use jdk1.4 logging api with weblogic 6.0

    Hi Everybody,
    Can anybody help me in configuring login configuration . Actually when i change the java_home in weblogic to jdk1.4, it starts throwing security exception like this:-
    java.lang.SecurityException
    at javax.security.auth.login.Configuration.getConfiguration(Configuration.java:229)
    at javax.security.auth.login.LoginContext$1.run(LoginContext.java:170)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.login.LoginContext.init(LoginContext.java:167)
    at javax.security.auth.login.LoginContext.<init>(LoginContext.java:393)
    at weblogic.security.internal.ServerAuthenticate.main(ServerAuthenticate.java:76)
    at weblogic.t3.srvr.T3Srvr.run(T3Srvr.java:167)
    at weblogic.Server.main(Server.java:35)
    if somebody can help in this regard,
    The following links can be used to refer to login configuration
    http://java.sun.com/j2se/1.4/docs/api/javax/security/auth/login/Configuration.html
    Regards,
    Neetika

    I am not sure what you mean by 'plug-in', but it sounds to me like you want to run weblogic with 1.4.
    And that probably isn't a good idea in a production system. 1.4 is still beta and there are suggestions that it still includes debugging code. And if bea hasn't certified it then you loose all support from them when running under that. This will all lead to extra time spent figuring out if the problem is in your code, in weblogic or in 1.4.

  • Practical use of java.lang.Error

    Hi All,
    I would like to know if we can use java.lang.Error -- the sibling of java.lang.Exception -- in our programme. If yes, how and for what practical purposes and if no, then what is the use of this class?
    Thanks,
    Abbas

    You would never normally subclass Error, nor catch
    and deal with such exceptions. I would disagree with this. If your application is
    improperly configured, use an Error. Provide very top
    level code to catch your specific Error (and perhaps
    others) so the user (and most likely the maintainers)
    can be properly notified, though note that you most
    likely will not be able to recover fully.I would say that should be an unchecked RuntimeException at best, but still not an "Error".
    >
    They are thrown by the
    VM when something "bad" happens such as runningout
    of memory.Unfortunately, they are not only thrown by the VM:
    CoderMalfunctionError
    FactoryConfigurationError
    TransformerFactoryConfigurationErrorI don't know what those Errors are (I know I could spend the time looking them up) but I bet they are standard java or javax - packaged errors, and the standard java or javax - packaged classes throw them right? If so, that is still what I mean by "throw by the VM".

  • Error in Using JDAPI (Java Development API)

    I have some forms developed in Version 6.0.8.8.0 I am using Oracle JDeveloper 9.0.4 But when I try to test these code for upgrading from version 6 to 10g I am getting following Error
    My Program Codes
    import java.io.*;
    import oracle.forms.jdapi.*;
    public class Example1 {
    // generic part
    public static void main(String[] args) {
    Jdapi.setFailLibraryLoad(true);
    Jdapi.setFailSubclassLoad(true);
    try {
    File file = new File("c:\\Amsorcl\\Forms\\chart.fmb");
    System.out.println("Exist=" + file.exists());
    System.out.println("Can Read=" + file.canRead());
    System.out.println("Can Write=" + file.canWrite());
    //JdapiModule.openModule(file);
    //JdapiModule.openModule("c:\\Amsorcl\\Forms\\chart.fmb");
    FormModule form = FormModule.open("C:\\AMSORCL\\FORMS\\CHART.FMB");
    finally {
    Jdapi.shutdown();
    Error as the result of progam
    Exist=true
    Can Read=true
    Can Write=true
    oracle.forms.jdapi.JdapiStatusException: jniinitialize: Failed to create new forms context
         at oracle.forms.jdapi.BaseAPI._jni_initialize(Native Method)
         at oracle.forms.jdapi.Jdapi.initialize(Unknown Source)
         at oracle.forms.jdapi.Jdapi.getContextPointer(Unknown Source)
         at oracle.forms.jdapi.FormModule.open(Unknown Source)
         at oracle.forms.jdapi.FormModule.open(Unknown Source)
         at Example1.main(Example1.java:22)
    Exception in thread main
    Process exited with exit code 1.

    1. Why are you using JDAPI to upgrade from 6i to 10g? You can use the Forms Migration Utility instead.
    2. Are you running this in UNIX environment? If yes, have you set the LD_LIBRARY_PATH to $ORACLE_HOME/lib directory?

  • Using a Java 5 API in a 1.4 project

    All my projects have to be developed in the Struts framework using Java 1.4.something but I really would like to use Watij web automation for a quick web scraping however it's Java 5. What is the best way to incorporate it into my project seeing as I can't directly use as it won't compile in my current project with Java 5.
    Here's the link if anyone is interested, it seems extremely interesting.
    http://watij.com/
    I already tried creating a Java 5 project, JARing it up and then just importing it in my struts project and calling the method I want however I end a
    java.lang.reflect.InvocationTargetException

    I think you may have to look at all your jar files in the project including struts jar packages, and watij home page, and verifying they all are java5 compatable. My guess is your error is caused by watij using java reflection to do something (assuming there is nothing in the project or struts using reflection) . You may try creating a small struts project that is java5 compatable and seeing if you can use the watij tool on it without an error. That way, you will isolate problems with watij and struts problem with java5, from who knows how many other problems the major project has with java5. Are you using a server such as tomcat? that has to be compatable with java5 too.

  • Accessing custom attributes in LDAP using WD Java - UME APIs

    Hello Friends,
    I am trying to access a custom attribute from LDAP in WebDynpro Java. I am using bellow code.
    IWDClientUser clientUser = WDClientUser.getCurrentUser();
    IUser sapUser = clientUser.getSAPUser();
    if (sapUser != null) {
    String[] str_emp = sapUser.getAttribute(<Name Space>,"Attribute Name");
    if (str_emp == null || str_emp.length == 0) {
    wdComponentAPI.getMessageManager().reportSuccess(" NULL ");
    return;
    } else {
    strEmpID = str_emp[0];
    wdComponentAPI.getMessageManager().reportSuccess(strEmpID);
    The name space is "$usermapping$". I am not sure why it is like that only for this attribute i am trying to access.
    I am getting null value if i run this code.
    Can any one help
    thanks
    Shobhan

    Hi,
    Are you sure this is the right namespace? The default namespace is com.sap.security.core.usermanagement.
    You can get all namespaces and the names of all attributes defined for a user using methods getAttributeNamespaces and getAttributeNames : [Interface IPrincipal|http://help.sap.com/javadocs/NW04S/current/se/index.html].
    Regards,
    Pierre

  • Java Logging API

    Hello,
    Can someone please explain when I would want to use FINE versus FINER versus FINEST for my log messages? Most tutorials explain roughly what these are, but I haven't seen anything that explains their use from a practitioner view. Some code would be very helpful, but I'll take anything less ambiguous than more, even more, even more more.

    Is my post worded poorly? I'm trying to figure out why nobody has replied (holidays?) Please let me know if this needs clarification. Thx.

Maybe you are looking for

  • Do I need a voltage converter?

    I'm going to Ireland from the US. Do I need to buy a voltage converter for my MacBook Pro or my iPhone 5s?

  • HT202447 Finder frizzes, makes my iMac so slow ...

    Since my system was updated automatically installing java 8, Finder frizzes, makes my computer so slow and I have to end up rebooting the computer. Any advise? How can I fix this problems? Thank you

  • I want to view my photos through icloud on my laptop but im finding it hard to do it

    I want to view all my photos on my icloud on my laptop but its not giving me the option, can u tell me how i do it or send me a link of some sort.thanks.

  • Find specific item based on itemproperty

    Trying to loop through some items in the registry to find the one that contains an itemproperty with a specific value ("VMware Tools"). I was thinking this would work: Get-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*" | Whe

  • Ejecting External HD

    I am using Time Machine with a 160 GB Maxtor USB 2.0 external hard drive. I frequently eject my computer from the external so I can take my MacBook places other than my room. When I plug the external back into my computer, I have been needing to manu