Jess Information

Jess Home
Jess 7 Features
Download Now!
Online Demo

Documentation
FAQ
Manual
Mailing List
Jess Wiki

More information Related Web Sites
User Contributions
JSR94 Info
Developer's Log
About This Site

JESS ®, the Rule Engine for the JavaTM Platform

Jess Wiki: Logger User Function

This user function, "logger", performs logging of messages using the Apache Commons Logging utility. The first argument is the name of the log. The second is the alert level: "trace", "debug", "info", "warn", "error", or "fatal". The final arguments represent the message(s) that needs to be logged. Example:
    Jess> (logger "com.mycomp.myapp.mylog" info Hello " World " 10 " " 99.99)
    [ INFO] Hello World 2007-01-18 08:06:22 Hello World 10 99.99 (Logger.java:call:189)

/* Logger.java
 * Created on Dec 7, 2004 by Ihfe020
 * Copyright Union Pacific Railroad
 */

package com.uprr.common.jess;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import jess.Context;
import jess.Funcall;
import jess.JessException;
import jess.RU;
import jess.Userfunction;
import jess.Value;
import jess.ValueVector;
//import jess.server.LineNumberRecord;
import jess.server.LineNumberRecord;

/** The Logger user function that defines "logger".
 * <P>Created on Dec 7, 2004</P>
 * @author George A. Williamson Jr. (Ihfe020)
 * @author ©Union Pacific Railroad
 */
public class Logger implements Userfunction {
    /** The logs */
    private static final transient Map logs =
        new HashMap();

    /** The newline string */
    private static final transient String newline =
        System.getProperty("line.separator");

    /** The log levels */
    private static final transient List logLevels =
        Arrays.asList(new String[] {
            "trace",
            "debug",
            "info",
            "warn",
            "error",
            "fatal" });

    /** Static initialization */
    {
        logs.put("", LogFactory.getLog(Logger.class));
    }

    /** Construct a new logger user function */
    public Logger() { super(); }

    /** Get the log for the given name */
    private static Log getLog
    (String logName)
    {
        Log log = (Log) logs.get(logName);
        if (log == null) {
            try {
                Class clazz = Class.forName(logName);
                log = LogFactory.getLog(clazz);
            }
            catch (Exception e) {
                log = LogFactory.getLog(logName);
            }
            logs.put(logName, log);
        }
        return log;
    }

    /** Get the logger user function name */
    public String getName() { return "logger"; }

    /** Get a string containing all the currently defined
     *  variables with their values
     */
    private String getVariableNamesString
    (Context context)
    throws JessException
    {
        StringBuffer sb = new StringBuffer();

        boolean first = true;
        for (Iterator itr = context.getVariableNames();
             itr.hasNext(); )
        {
            String variableName = (String) itr.next();
            if (!variableName.startsWith("%")) {
                if (first) { first = false; }
                else { sb.append(", "); }
                sb.append(variableName + " = " +
                    context.getVariable(variableName));
            }
        }

        return sb.toString();
    }

    /** Get the file and line number string */
    private String getFileLineNumberString
    (Context context)
    {
        try {
            LineNumberRecord lnr = context.getLineNumberRecord();

            String filename;
            if (context != null && lnr != null &&
                (filename = lnr.getFileName()) != null)
            {
                String variables = "";
                try { variables = getVariableNamesString(context); }
                catch (JessException e) {}
                return " (" + filename + ":" + lnr.getLineno() +
                       (variables.length() != 0
                            ? " - " + variables
                            : "") +
                        ")";
            }
        }
        catch (Exception e) {}
        return "";
    }

    /** Get the log message text */
    private String getLogText
    (int startIndex, ValueVector vv, Context context)
    throws JessException
    {
        StringBuffer sb = new StringBuffer();

        for (int i = startIndex; i < vv.size(); i++) {
            Value v = vv.get(i).resolveValue(context);
            if (v.type() == RU.STRING) {
                sb.append(v.stringValue(context));
            }
            else if (v.type() == RU.SYMBOL &&
                     v.symbolValue(context).equals("crlf"))
            {
                sb.append(newline);
            }
            else {
                sb.append(v);
            }
        }
        sb.append(getFileLineNumberString(context));

        return sb.toString();
    }

    /** Call the logger user function */
    public Value call
    (ValueVector vv, Context context)
    throws JessException
    {
        String logName = vv.get(1).stringValue(context);
        String level;

        // Get the log name and level
        int startIndex;
        if (logLevels.contains(logName.toLowerCase())) {
            level = logName;
            logName = "";
            startIndex = 2;
        }
        else {
            level = vv.get(2).stringValue(context);
            startIndex = 3;
        }

        // Get the log
        Log log = getLog(logName);

        // Write the log message
        if (level.equalsIgnoreCase("fatal")) {
            if (log.isFatalEnabled()) {
                log.fatal(getLogText(startIndex, vv, context));
            }
        }
        else if (level.equalsIgnoreCase("error")) {
            if (log.isErrorEnabled()) {
                log.error(getLogText(startIndex, vv, context));
            }
        }
        else if (level.equalsIgnoreCase("warn")) {
            if (log.isWarnEnabled()) {
                log.warn(getLogText(startIndex, vv, context));
            }
        }
        else if (level.equalsIgnoreCase("info")) {
            if (log.isInfoEnabled()) {
                log.info(getLogText(startIndex, vv, context));
            }
        }
        else if (level.equalsIgnoreCase("debug")) {
            if (log.isDebugEnabled()) {
                log.debug(getLogText(startIndex, vv, context));
            }
        }
        else if (level.equalsIgnoreCase("trace")) {
            if (log.isTraceEnabled()) {
                log.trace(getLogText(startIndex, vv, context));
            }
        }
        else {
            throw new JessException(
                getName(),
                "Unknown logging level: " + level,
                level);
        }
        return Funcall.NIL;
    }
}

Submitted by:
GeorgeWilliamson
Union Pacific Railroad
gawillia@up.com



UserFunctionExamples


Front Page | Sandbox | Recent Changes | Powered by Friki | Last Edited: 18 January 2007