Showing posts with label logging. Show all posts
Showing posts with label logging. Show all posts

Friday, June 24, 2016

Log4j2 java.util.logging (JUL) Adapter Example

Introduction


I was looking for an example of how to implement the java.util.logging (JUL) adapter in a project. This would almost seem to be a no brainer of an idea with lots of examples of how to do it. Alas, I didn't find much of anything. So I thought I would share some wisdom of how to implement the JUL Adapter.

Implementation


You need to tell the application to use the JUL adapter. There are two easy ways to accomplish this.
  1. The easiest is to pass a VM option to the application: -Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager
  2. Alternatively, you can use a static initializer in your class. This is important because the value needs to be set before the logger is called.

The code for the project can be found on GitHub here: log4j2-jul-example

Code


Thursday, July 10, 2014

A simple practical "pragmatic" Formatter for java.util.logging.Logger

I have quite a trove of code examples I have collected over the years. Here is another example of a Formatter used with the java.util.logging.Logger to generate a standard output.

PragmaticFormatter.java


The next question is how do you use it? Easy enough... here is an example for you. The code for the project is located here: pragmatic-logging-formatter

Tuesday, May 31, 2011

Logging to a File - Using a FileHandler

Java has a built in logging mechanism. This mechanism was adding to provide logging functionality to the base Java libraries. This removes external dependencies from your project, and allows you to use logging within the base framework.

Log4J has an incredible amount functionality, but requires that you add the framework to your project and its dependencies. There is also configuration required up front to use the logging.

The default logging mechanism is very easy to use. We simply create a Logger instance from the static class. Using it is as simple as calling Logger.getAnonymousLogger();. This allows you to create an anonymous logger which is a console logger. There is no default mechanism for logging to the file system. This accomplished by using a FileHandler.

A simple sample implementation is located below. I have please note the comments. The NetBeans project is located here: ExampleLogger.zip

ExampleLogger.java


/*
 * Copyright 2011 John Yeary <jyeary@bluelotussoftware.com>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bluelotussoftware.example;

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author John Yeary <jyeary@bluelotussoftware.com>
 * @version 1.0
 */
public class LoggerExample {

    private static final Logger logger = Logger.getLogger(LoggerExample.class.getName());
    private FileHandler fileHandler;

    public LoggerExample() {
        /*
         * This is one option using the FileHandler in the constructor
         * for the class. This will work if we need to instantiate
         * the class before use. In the case of a class where the main()
         * method is located we should consider a separate case in
         * the main method to initialize the handler. (See below)
         */
        addFileHandler(logger);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        logger.info("main() method called.");

        /*
         * Instantiating the class with actually create two
         * FileHandlers.
         */
        LoggerExample le = new LoggerExample();

        /*
         * Anonymous inner class method for adding a FileHandler
         * in main() method.
         */
        try {
            logger.info("Adding FileHandler");
            logger.addHandler(new FileHandler(LoggerExample.class.getName()
                    + ".main.log"));
            logger.info("Added FileHandler to Logger");
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            logger.log(Level.SEVERE, null, ex);
        }

        // Example logging.
        logger.info("Logging for fun and profit");
        logger.fine("Fine...");
        logger.finer("Finer...");
        logger.finest("Finest...");
        logger.warning("Warning...");
        logger.severe("Severe...");
        logger.info("Logging complete.");
    }

    /**
     * Add a <code>FileHandler</code> to the provided <code>Logger</code>.
     * @param logger <code>Logger</code> to add <code>FileHandler</code>.
     */
    private void addFileHandler(Logger logger) {
        try {
            fileHandler = new FileHandler(LoggerExample.class.getName() + ".log");
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
        logger.addHandler(fileHandler);
    }
}
Enhanced by Zemanta

Wednesday, October 27, 2010

Disabling Apache POI Logging

Jakarta POI LogoImage via Wikipedia
In order to effectively disable the logging functionality in Apache POI you must use an alternative logger. This is accomplished by providing a property to the POILogFactory to override the default logger. Examining the partial code from the POILogFactory, we see that we can pass a logger name into it.

public static POILogger getLogger(final String cat)
    {
        POILogger logger = null;
        
        // If we haven't found out what logger to use yet,
        //  then do so now
        // Don't look it up until we're first asked, so
        //  that our users can set the system property
        //  between class loading and first use
        if(_loggerClassName == null) {
         try {
          _loggerClassName = System.getProperty("org.apache.poi.util.POILogger");//<<---------- Logger Name
         } catch(Exception e) {}
         
         // Use the default logger if none specified,
         //  or none could be fetched
         if(_loggerClassName == null) {
          _loggerClassName = _nullLogger.getClass().getName();
         }
        }
...
So we need to simply set the Logger property which can be accomplished from the command line. We will use the Apache Commons Logging Library to accomplish it.
-Dorg.apache.poi.util.POILogger=org.apache.commons.logging.impl.NoOpLog
Enhanced by Zemanta

Disabling Logging on Apache Commons Logger

I was looking for a quick way to disable logging on Apache Commons Logger so that I could do some testing without overhead. Here is a command line option for setting the logger to a no-op logger.

-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.NoOpLog

Thursday, December 20, 2007

Pragmatic Logging

After reading the book Release It! I decided to write a quick extension to the Java Logging framework from the JDK. I called it PragmaticLogging. It is a Netbeans 6.0 project. I have released it under the Apache 2.0 License.

The idea was to provide a simple extension to the JDK which would make logging easier for developers and administrators.

There is another zipped Netbeans project called PragmaticLoggingExample which will use the Pragmatic Logging framework to generate some example logging output.

The project is completely documented (If you see something missing... leave a comment).

If you have any suggestions/enhancements please post a comment and I will see about updating the framework.

Popular Posts