pyx4j-utils

Overview

The pyx4j-utils project is a collection of java classes we used in all our projects

  • AppConfiguration - Application configuration utility, wrapper for JFig
  • Logger - Wrapper for Log4j logger, we find it is easier to use it.
  • DeepToStringStyle - used in Logger to print Reflection of beans. Extension to apache.commons.lang.ReflectionToStringBuilder

Usage

This fragment from log4j.xml for RollingFileAppender.

    <appender name="FILE" class="com.pyx4j.log.RollingFileAppender">
        <param name="contextNameDefault" value="web"/>
        <param name="File" value="${app.log4j.dir}/app-%{contextName}.log"/>

        <param name="Append" value="true"/>

        <!-- start new file on every restart -->
        <param name="InitialyRollOver" value="true"/>

        <param name="MaxFileSize" value="2000KB"/>

        <!-- RetentionDuration specifies number of days to keep log file before clean-up -->
        <param name="RetentionDuration" value="14"/>
        <param name="MaxBackupIndex" value="7"/>

        <!-- RealFileName = File + FileNameOpenPattern + FileNameClosePattern + (.#) -->
        <param name="FileNameOpenPattern" value=".yyyy-MM-dd_HH-mm"/>
        <param name="FileNameClosePattern" value=" - yyyy-MM-dd_HH-mm"/>

        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d \t (%t){%X{sessionNum}.%X{userID}.%x}(%c{1})\t %l%n \t%m%n" />
        </layout>
    </appender>

There is special variable %contextName that would be replaced by appender. This allow you to use ServletContextListener to initialize file names differently for multiple deployment instances of application. This should be done before Log4j initialized.

public class AppConfiguratorContextListener implements ServletContextListener {

    /* (non-Javadoc)
     * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent sce) {
        String name = getContextName(sce);
        RollingFileAppender.setContextName(name);
        //Logger.setContextName(name);
    }

    private String getContextName(ServletContextEvent sce) {
        final String find = "/index.html";
        String p = sce.getServletContext().getRealPath(find);
        if (p == null) {
                return null;
        }
        p = p.substring(0, p.length() - find.length());
        int idx = p.lastIndexOf('/');
        if (idx == -1) {
            idx = p.lastIndexOf('\\');
        }
        if (idx == -1) {
                return null;
        }
        return p.substring(idx + 1);
    }
    ...

Logger usage example

public class AppExample {

    private static final Logger log = Logger.getLogger();

    public void lateToStringCall() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("bean1", new SimpleBean());
        log.debug("map", map);
    }

}