The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util.logging  [20 examples]

e393. Writing Log Records Only After a Condition Occurs

Suppose you are trying to track down an infrequent bug on a production system with copious amounts of debug log messages. In most cases, when the bug occurs, it is not necessary to have the entire history of log messages; only a recent few are needed. To minimize the impact on the system, a MemoryHandler can be used to store a number of log records in memory and then dump them out only if the bug or other condition occurs.
    try {
        // Create a memory handler with a memory of 100 records
        // and dumps the records into the file my.log when a
        // SEVERE message is logged
        FileHandler fhandler = new FileHandler("my.log");
        int numRec = 100;
        MemoryHandler mhandler = new MemoryHandler(fhandler, numRec, Level.SEVERE);
    
        // Add to the desired logger
        Logger logger = Logger.getLogger("com.mycompany");
        logger.addHandler(mhandler);
    } catch (IOException e) {
    }
    
    try {
        // Create a memory handler with a memory of 100 records
        // and dumps the records into the file my.log when a
        // some abitrary condition occurs
        FileHandler fhandler = new FileHandler("my.log");
        int numRec = 100;
        MemoryHandler mhandler = new MemoryHandler(fhandler, numRec, Level.OFF) {
            public synchronized void publish(LogRecord record) {
                // Log it before checking the condition
                super.publish(record);
    
                boolean condition = false;
                if (condition) {
                    // Condition occurred so dump buffered records
                    push();
                }
            }
        };
    
        // Add to the desired logger
        Logger logger = Logger.getLogger("com.mycompany");
        logger.addHandler(mhandler);
    } catch (IOException e) {
    }

 Related Examples
e385. The Quintessential Logging Program
e386. Determining If a Message Will Be Logged
e387. Logging a Method Call
e388. Logging an Exception
e389. Minimizing the Impact of Logging Code
e390. Preventing a Logger from Forwarding Log Records to Its Parent
e391. Writing Log Records to a Log File
e392. Writing Log Records to Standard Error
e394. Setting a Filter on a Logger Handler

See also: Configuration    File Size    Formatters    Levels   


© 2002 Addison-Wesley.