9 Replies Latest reply on Jan 4, 2013 12:28 PM by jamezp

    How to create custom logger that uses properties

      Hi,

      I tried to get a custom logger working and looked at some examples like this one https://community.jboss.org/wiki/CreatingACustomLoggingHandlerInJBOSSAs710Final, but my problem is that the properties are always ignored.

       

      So I have my custom logger which extends Handler and I have some field like "fileName" with public setter, but now when I try to set these properties in the config like this

       

      <custom-handler ...

        <properties>

          <property name="fileName" value="myTest.log" />

        </properties>

      </custom-handler>

       

      it is always irgnored.

       

      Do I have to do something in the code to get the values from the config?

        • 1. Re: How to create custom logger that uses properties
          jamezp

          What is the setter method name? It needs to be setFileName(String s) in the example you have.

           

          --

          James R. Perkins

          • 2. Re: How to create custom logger that uses properties

            The setter is following the JavaBeans conventions

             

            public void setFileName(String fileName) {

                    this.fileName = fileName;

                }

            • 3. Re: How to create custom logger that uses properties
              nickarls

              Show the code for the entire handler and the complete code for the custom-handler registration

              • 4. Re: How to create custom logger that uses properties

                Here is the code. The logger should do a daily rolling and compression of old logs. But at the moment it is always only creating the default log file ("customLogging.log").

                 

                package net.codeplumber.util.logger;

                 

                import java.io.BufferedOutputStream;

                import java.io.File;

                import java.io.FileFilter;

                import java.io.FileInputStream;

                import java.io.FileOutputStream;

                import java.io.IOException;

                import java.text.SimpleDateFormat;

                import java.util.ArrayList;

                import java.util.Calendar;

                import java.util.Date;

                import java.util.List;

                import java.util.Locale;

                import java.util.TimeZone;

                import java.util.logging.ErrorManager;

                import java.util.logging.Filter;

                import java.util.logging.Formatter;

                import java.util.logging.Level;

                import java.util.logging.LogManager;

                import java.util.logging.LogRecord;

                import java.util.logging.StreamHandler;

                import java.util.logging.XMLFormatter;

                import java.util.zip.GZIPOutputStream;

                 

                 

                import org.apache.log4j.helpers.LogLog;

                 

                 

                public class CustomDailyRollingLoggingHandler extends StreamHandler {

                 

                 

                    private static final CustomDailyRollingCalendar ROLLING_CALENDAR = new CustomDailyRollingCalendar(

                            TimeZone.getTimeZone("GMT"), Locale.ENGLISH);

                    private static final String DATE_PATTERN = "'.'yyyy-MM-dd";

                    private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat(DATE_PATTERN);

                 

                 

                    private int maxNumberOfDays;

                    private String fileName;

                    private boolean compressBackups = true;

                   

                    private String scheduledFilename;

                    private long nextCheck = System.currentTimeMillis() - 1;

                    private Date now = new Date();

                 

                 

                    public CustomDailyRollingLoggingHandler() throws IOException, SecurityException {

                        checkAccess();

                        configure();

                        open(new File(fileName));

                    }

                 

                 

                    private void open(File fname) throws IOException {

                        FileOutputStream fout = new FileOutputStream(fname.toString(), true);

                        BufferedOutputStream bout = new BufferedOutputStream(fout);

                        setOutputStream(bout);

                    }

                 

                 

                    private void configure() {

                        LogManager manager = LogManager.getLogManager();

                 

                 

                        String cname = getClass().getName();

                 

                 

                        if (fileName == null || fileName.length() == 0) {

                            fileName = getStringProperty(manager, cname + ".fileName", "customLogging.log");

                        }

                 

                 

                        if (maxNumberOfDays <= 0) {

                            maxNumberOfDays = getIntProperty(manager, cname + ".maxNumberOfDays", 1);

                        }

                        if (maxNumberOfDays <= 0) {

                            maxNumberOfDays = 1;

                        }

                 

                 

                        String compressBackupsFromSysProp = manager.getProperty(cname + ".compressBackups");

                        if (compressBackupsFromSysProp != null) {

                            compressBackups = getBooleanProperty(manager, cname + ".compressBackups", true);

                        }

                        setLevel(getLevelProperty(manager, cname + ".level", Level.ALL));

                        setFilter(getFilterProperty(manager, cname + ".filter", null));

                        setFormatter(getFormatterProperty(manager, cname + ".formatter", new XMLFormatter()));

                        try {

                            setEncoding(getStringProperty(manager, cname + ".encoding", null));

                        } catch (Exception ex) {

                            try {

                                setEncoding(null);

                            } catch (Exception ex2) {

                                // doing a setEncoding with null should always work.

                                // assert false;

                            }

                        }

                 

                 

                        ROLLING_CALENDAR.setType(CustomDailyRollingCalendar.TOP_OF_DAY);

                        File file = new File(fileName);

                        scheduledFilename = fileName + SIMPLE_DATE_FORMAT.format(new Date(file.lastModified()));

                    }

                 

                 

                    private void checkAccess() {

                        LogManager manager = LogManager.getLogManager();

                        manager.checkAccess();

                    }

                 

                 

                    protected void cleanupAndRollOver() {

                        // Omitted

                    }

                 

                 

                    public synchronized void publish(LogRecord record) {

                        if (!isLoggable(record)) {

                            return;

                        }

                 

                 

                        long n = System.currentTimeMillis();

                        if (n >= nextCheck) {

                            now.setTime(n);

                            nextCheck = ROLLING_CALENDAR.getNextCheckMillis(now);

                 

                 

                            cleanupAndRollOver();

                 

                 

                        }

                 

                 

                        super.publish(record);

                        flush();

                 

                 

                    }

                 

                 

                    public synchronized void close() throws SecurityException {

                        super.close();

                    }

                 

                 

                    public int getMaxNumberOfDays() {

                        return maxNumberOfDays;

                    }

                 

                 

                    public void setMaxNumberOfDays(int maxNumberOfDays) {

                        this.maxNumberOfDays = maxNumberOfDays;

                    }

                 

                 

                    public void setMaxNumberOfDays(String maxNumberOfDays) {

                        try {

                            this.maxNumberOfDays = Integer.parseInt(maxNumberOfDays);

                        } catch (NumberFormatException e) {

                            this.maxNumberOfDays = 1;

                        }

                    }

                 

                 

                    public String getFileName() {

                        return fileName;

                    }

                 

                 

                    public void setFileName(String fileName) {

                        this.fileName = fileName;

                    }

                 

                 

                    public boolean isCompressBackups() {

                        return compressBackups;

                    }

                 

                 

                    public void setCompressBackups(boolean compressBackups) {

                        this.compressBackups = compressBackups;

                    }

                 

                 

                    public void setCompressBackups(String compressBackups) {

                        if ("true".equals(compressBackups)) {

                            this.compressBackups = true;

                        } else {

                            this.compressBackups = false;

                        }

                    }

                }

                 

                The part from the standalone.xml is here

                 

                <subsystem xmlns="urn:jboss:domain:logging:1.1">

                            <custom-handler name="DAILY_ROLLING_CUSTOM_HANDLER" class="net.codeplumber.util.logger.CustomDailyRollingLoggingHandler" module="net.codeplumber.util">

                                <level name="DEBUG"/>

                                <formatter>

                                    <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>

                                </formatter>

                                <properties>

                                    <property name="maxNumberOfDays" value="90"/>

                                    <property name="fileName" value="/home/tom/tomsTest.log"/>

                                    <property name="compressBackups" value="true"/>

                                </properties>

                            </custom-handler>

                            <periodic-rotating-file-handler name="FILE">

                                <formatter>

                                    <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>

                                </formatter>

                                <file relative-to="jboss.server.log.dir" path="server.log"/>

                                <suffix value=".yyyy-MM-dd"/>

                                <append value="true"/>

                            </periodic-rotating-file-handler>

                            <logger category="com.arjuna">

                                <level name="WARN"/>

                            </logger>

                            <logger category="org.apache.tomcat.util.modeler">

                                <level name="WARN"/>

                            </logger>

                            <logger category="sun.rmi">

                                <level name="WARN"/>

                            </logger>

                            <logger category="jacorb">

                                <level name="WARN"/>

                            </logger>

                            <logger category="jacorb.config">

                                <level name="ERROR"/>

                            </logger>

                            <logger category="net.codeplumber" use-parent-handlers="true">

                                <level name="DEBUG"/>

                                <handlers>

                                    <handler name="DAILY_ROLLING_CUSTOM_HANDLER"/>

                                </handlers>

                            </logger>

                            <root-logger>

                                <level name="INFO"/>

                                <handlers>

                                    <handler name="FILE"/>

                                </handlers>

                            </root-logger>

                        </subsystem>

                • 5. Re: How to create custom logger that uses properties
                  nickarls

                  Have you tried having the logger just extending java.util.logging.Handler?

                  • 6. Re: How to create custom logger that uses properties

                    No change in behaviour after extending java.util.logging.Handler.

                    • 7. Re: How to create custom logger that uses properties
                      nickarls

                      I think you are using the fileName too early. You call configure() in the constructor but the log subsystem probably creates the class and then calls the setters on it. Put some system.out.println in the setter to check if the theory is correct.

                      1 of 1 people found this helpful
                      • 8. Re: How to create custom logger that uses properties

                        Yes you are right. After moving the configure() into the publish() method it is getting the value from the config.

                        • 9. Re: How to create custom logger that uses properties
                          jamezp

                          You could extend org.jboss.logmanager.handlers.FileHandler. There is a preWrite() method that would allow you to check whether the log should be rotated or not. It looks like the handler you're using won't allow for many runtime changes. Well maybe it will when a new record is published, but not until then :-)

                           

                          You can look at the PeriodicRotatingFileHandler as it's very similar to what you're doing.

                           

                          --

                          James R. Perkins