Caucho maker of Resin Server | Application Server (Java EE Certified) and Web Server


 

Resin Documentation

home company docs 
app server 
 Resin Server | Application Server (Java EE Certified) and Web Server
 

logging


Resin can perform access logging, specify where JDK logging interface messages go, and redirect the stderr and stdout for your applications.

java.util.logging

Overview

Resin uses the JDK standard java.util.logging for all its internal logging and offers flexible configuration for the logging format and the logging level. The logging configuration has two parts: the set of log handlers, and the logger level.

A log handler tells Resin where to send logging output. Resin includes file-based log handlers, mail handlers, syslog handlers, and any custom logging handler following the JDK standard. The log handler is configured with a name and a level which must both match for the log to be output.

Example: file-based log-handler in resin.xml
<resin xmlns="http://caucho.com/ns/resin">

  <log-handler name="com.foo" level="all"
               path="${resin.root}/log/foo.log"
               timestamp="[%y-%m-%d %H:%M:%S.%s] {%{thread}} "/>
  ...
  
</resin>  

The <logger> configures the logging level for a named logger. Because a <logger> will generally have several log-handlers, both the logger level and the log-handler level must match for the log to output. Since the logger and log-handler names are hierarchical, a "com.foo" <logger> will enable "com.foo.bar".

Example: logging at the 'fine' level in resin.xml
<resin xmlns="http://caucho.com/ns/resin">

  <logger name="com.foo" level="fine"/>
  <logger name="com.foo.bar" level="finest"/>
  ...
  
</resin>  

Log names

The JDK logging api uses a hierarchical naming scheme. Typically the name is aligned with a java class name. When you specify a name, all logging requests that use a name that starts with the name you have specified are matched. For example: <logger name="example.hogwarts" ...> matches a logging request for both "example.hogwarts.System" and "example.hogwarts.gryffindor.System"

Resin's own logging is based on Resin's source class names. The following are useful log names in Resin:

Resin log names
NAMEMEANING
""Debug everything
com.caucho.ejbEJB handling
com.caucho.jspDebug jsp
com.caucho.javaJava compilation
com.caucho.server.portTCP port debugging and threading
com.caucho.server.httpHTTP-related debugging
com.caucho.server.webappweb-app related debugging
com.caucho.server.cacheCache related debugging
com.caucho.sqlDatabase pooling
com.caucho.transactionTransaction handling

Log levels

The logger level enables logs for a given debugging granularity. A "severe" level only shows logs which threaten the stability of the server, and a "fine" level shows debugging information intended for application/library users.

The logger levels match the values defined by the JDK java.util.logging.Level.

Logging Level values
NAMEAPISUGGESTED USE
off turn off logging
severelog.severe("...")a major failure which prevents normal program execution, e.g. a web-app failing to start or a server restart
warninglog.warning("...")a serious issue, likely causing incorrect behavior, like a 500 response code to a browser
infolog.info("...")major lifecycle events, like a web-app starting
configlog.config("...")detailed configuration logging
finelog.fine("...")debugging at a user level, i.e. for someone not familiar with the source code being debugged
finerlog.finer("...")detailed debugging for a developer of the code being debugged
finestlog.finest("...")events not normally debugged, e.g. expected exceptions logged to avoid completely swallowing, or Hessian or XML protocol parsing
all all messages should be logged

<log-handler>

Configure a log handler for the JDK java.util.logging API. java.util.logging has two steps: configure a set of log handlers, and configure the levels for each logger. The <log-handler> creates a destination for logs, sets a minimum logging level for the handler, and attaches the handler to a logging name.

In addition to configuring custom handlers, <log-handler> has the most common configuration built-in: logging to a rotating file. Most of the configuration attributes are used for the rotating file and are shared with the other logging configuration.

log-handler timestamp

The timestamp for log tags is a format string which can contain percent codes which are substituted with time and date values.

CODEMEANING
%aday of week (short)
%Aday of week (verbose)
%bday of month (short)
%Bday of month (verbose)
%cJava locale date
%dday of month (two-digit)
%H24-hour (two-digit)
%I12-hour (two-digit)
%jday of year (three-digit)
%mmonth (two-digit)
%Mminutes
%pam/pm
%Sseconds
%smilliseconds
%Wweek in year (three-digit)
%wday of week (one-digit)
%yyear (two-digit)
%Yyear (four-digit)
%Ztime zone (name)
%ztime zone (+/-0800)
%{thread}Current thread name
%{level}Current logging level
%{env}Current class-loader environment
Example: typical timestamp for the log tag
<resin xmlns="http://caucho.com/ns/resin">

  <log-handler name='' path='stderr:' timestamp="[%H:%M:%S.%s] {%{thread}}"/>

  ...
</resin>
[22:50:11.648] WebApp[/doc] starting
[22:50:11.698] http listening to *:8080
[22:50:11.828] hmux listening to *:6800

log-handler archiving

The following example is a standard log handler writing to a rollover file. Because the handler's level is "all", the <logger> configuration will set the actual logging level.

Example: logging to a rollover file
<web-app xmlns="http://caucho.com/ns/resin">

  <log-handler name="" level="all"
       timestamp="[%Y/%m/%d %H:%M:%S.%s] {%{thread}} "/>

  <logger name="com.caucho" level="info"/>

</web-app>

The default archive format is

default archive-format
path + ".%Y%m%d"    if rollover-period >= 1 day.
path + ".%Y%m%d.%H" if rollover-period < 1 day.

For example, to log everything to standard error use:

Example: logging everything to System.err
<resin xmlns="http://caucho.com/ns/resin">
  <log-handler name="" level="all" path="stderr:" timestamp="[%H:%M:%S.%s]"/>
  ...
</resin>

A useful technique is to enable full debug logging to track down a problem:

debug logging

<resin>
  ...
  <log-handler name="" level="finer" path="log/debug.log"
       timestamp="[%H:%M:%S.%s]"
       rollover-period="1h" rollover-count="1"/>
  ...
</resin>

log-handler EL formatting

The format for Resin's log-handler tags specifies a format string for each log message. format recognizes EL-expressions. The EL variable log is a com.caucho.log.ELFormatter#ELFormatterLogRecord object.

Example: log format string

<log-handler name="" level="all" path="stderr:" timestamp="[%H:%M:%S.%s]"
     format=" ${log.level} ${log.name} ${log.message}"/>

log EL variable 'log' is a LogRecord
ACCESSORVALUE
${log.level}The level of the log record
${log.name}The source loggers name
${log.shortName}A shorter version of the source loggers name, "Foo" instead of "com.hogwarts.Foo"
${log.message}The message, with no formatting or localization
${log.millis}event time in milliseconds since 1970
${log.sourceClassName}Get the name of the class that issued the logging request (may not be available at runtime)
${log.sourceMethodName}Get the name of the method that issued the logging request (may not be available at runtime)
${log.threadID}Get an int identifier of the thread where the logging request originated
${log.thrown}Get any java.lang.Throwable associated with the logging request
${thread}The name of the current thread.
${request}The servlet request value.
${session}The servlet session.
${cookie['JSESSIONID']}The value of a request cookie.

You can also use the Environment EL variables in your format string:

log format string using an Environment EL variable.
<host ...>

  <web-app>
    <log name='' level='all' path='log/debug.log' timestamp="[%H:%M:%S.%s]"
         format=" [${app.contextPath}] ${log.message}"/>

    ...
  </web-app>

  ...

</host>
[14:55:10.189] [/foo] `null' returning JNDI java:
       model for EnvironmentClassLoader[web-app:http://localhost:8080/foo]
[14:55:10.189] [/foo] JNDI lookup `java:comp/env/caucho/auth'
       exception javax.naming.NameNotFoundException: java:comp/env/caucho/auth
[14:55:10.199] [/foo] Application[http://localhost:8080/foo] starting

The fmt.sprintf() function can space pad the values and make the results look a little nicer:

fmt.sprintf() in log format string
<log name="" level="all" path="stderr:" timestamp="[%H:%M:%S.%s]"
     format=" ${fmt.sprintf('%-7s %45s %s',log.level,log.loggerName,log.message)}">
[14:28:08.137] INFO com.caucho.vfs.QJniServerSocket Loaded Socket JNI library.
[14:28:08.137] INFO com.caucho.server.port.Port http listening to *:8080
[14:28:08.137] INFO com.caucho.server.resin.ServletServer ServletServer[] starting
[14:28:08.307] INFO com.caucho.server.port.Port hmux listening to localhost:6802
[14:28:08.437] INFO com.caucho.server.host.Host Host[] starting 

fmt.sprintf() and fmt.timestamp() can be used to produce CSV files:

CSV log files
<log name="" level="all" path="log/debug.csv" timestamp=""
     format="${fmt.sprintf('%vs,%d,%d,%vs,%vs',fmt.timestamp('%Y-%m-%d %H:%M:%S.%s'), 
               log.threadID, log.level.intLevel(), log.loggerName, log.message)}"/>
"2003-11-17 14:46:14.529",10,800,"com.caucho.vfs.QJniServerSocket",
            "Loaded Socket JNI library."
"2003-11-17 14:46:14.549",10,800,"com.caucho.server.port.Port",
            "http listening to *:8080"
"2003-11-17 14:46:14.549",10,800,"com.caucho.server.resin.ServletServer",
            "ServletServer[] starting"
"2003-11-17 14:46:14.719",10,800,"com.caucho.server.port.Port",
            "hmux listening to localhost:6802"
"2003-11-17 14:46:14.850",10,800,"com.caucho.server.host.Host",
            "Host[] starting"
"2003-11-17 14:46:15.100",10,800,"com.caucho.server.webapp.Application",
            "Application[http://localhost:8080/freelistbm] starting"

Logger: Application logging

You can take advantage of the JDK's logging facility to add logging to your application. Choosing a good logging name and levels are important for troubleshooting and debugging your code. Logging to much can be almost as confusing as logging too little.

The logging name should be the full class name of the class you're instrumenting. Although other schemes are possible, the class name is more maintainable.

The logging level should be consistent across your application. For Resin, we use the following level conventions:

Example: logging at finer
import java.util.logging.Logger;
import java.util.logging.Level;

public class Foo {
  private static final Logger log
    = Logger.getLogger(Foo.class.getName());

  ...
  void doFoo(String bar)
  {
    // check for log level if your logging call does anything more
    // than pass parameters
    if (log.isLoggable(Level.FINER))
        log.finer(this + "doFoo(" + bar + ")");

    ...

    log.info(...);

    try {
        ...
    } catch (ExpectedException ex) {
      log.log(Level.FINEST, "expected exception", ex);
    }
  }
  ...
}

Custom and library log handlers

Custom handlers and log handlers from libraries can be configured with Resin's logging system, using the CanDI XML configuration syntax. The custom handler is a child of <log-handler> and configured with any argument or setters necessary. Resin will install the handler just like one of its own handlers.

Example: JDK's FileHandler
<web-app xmlns="http://caucho.com/ns/resin"
   xmlns:jdk-logging="urn:java.util.logging">

  <log-handler name="com.foo" level="info">
    <jdk-logging:FileHandler>
      <new>
        <value>/tmp/test.out</value>
      </new>
    </jdk-logging:FileHandler>
  </logger>
  
</web-app>
Example: MyHandler.java
package com.foo.demo;

import java.util.logging.*;

public class MyHandler extends Handler
{
  @Override
  public void publish(LogRecord record)
  {
    System.out.println(getFormatter().format(record));
  }
  
  @Override
  public void flush();
  {
  }
  
  @Override
  public void close();
  {
  }
}

Custom log formatting

The formatting of a log message can be customized just like the log handler. The Formatter is a java.util.logging interface which Resin's logging understands and can be configured with <log-handler>.

Sites may wish to change the formatting of log messages to gather information more appropriate for the site. The formatter can be custom-configured just like the handlers.

Example: custom formatter configuration
<web-app xmlns="http://caucho.com/ns/resin"
  xmlns:mypkg="urn:java:com.mycom.mypkg">

  <log-handler name="com.foo" level="warning" path="WEB-INF/log.log">
    <formatter><mypkg:MyFormatter/></formatter>
  </log-handler>
  
</web-app>
Example: MyFormatter.java
package com.mycom.mypkg;

import java.util.logging.*;

public class MyFormatter extends Formatter
{
  @Override
  public String format(LogRecord record)
  {
    return "[" + record.getLevel() + "] " + record.getMessage();
  }
}

Resin Builtin Log Handlers

Resin provides a number of predefined custom log handlers for common logging patterns, including sending messages to JMS, HMTP, and the syslog service. Creating your own custom handler is also straightforward.

BamLogHandler (4.0.5)

The BAM handler publishes the log message to a BAM agent. The agent can be a custom HMTP service to process log messages. The BamHandler needs a JID (Jabber id) as the address of the target service.

Example: BAM handler configuration
<web-app xmlns="http://caucho.com/ns/resin"
  xmlns:resin="urn:java:com.caucho.resin">

  <logger name="com.foo">
    <resin:BamLogHandler level="warning">
       <to>test@localhost</to>
    </resin:BamLogHandler>
  </logger>

</web-app>

EventLogHandler

The event handler publishes a java.util.logging.LogRecord to the CanDI event system. Any CanDI component with an @Observes method for LogRecord will receive the notifications. The log handler classname is com.caucho.log.EventHandler.

Example: event handler configuration
<web-app xmlns="http://caucho.com/ns/resin"
   xmlns:resin="urn:java:com.caucho.resin">

  <logger name="com.foo">
    <resin:EventHandler level="warning"/>
  </logger>

</web-app>

JmsLogHandler

The JMS handler publishes the log message to a JMS queue.

Example: JMS handler configuration
<web-app xmlns="http://caucho.com/ns/resin"
    xmlns:ee="urn:java:ee"
    xmlns:resin="urn:java:com.caucho.resin">

  <resin:MemoryQueue ee:Named="myQueue"/>

  <logger name="com.foo">
    <resin:JmsLogHandler level="warning">
       <target>${myQueue}</target>
   </resin:JmsLogHandler>
  </logger>

</web-app>

MailLogHandler (4.0.5+)

The Mail handler sends log messages to an email address. To keep the number of mails down, the handler will concatenate messages and only send them after a period of time.

MailLogHandler attributes
ATTRIBUTEDESCRIPTIONDEFAULT
tomail addressrequired
delay-timetime to wait before sending first mail1m
mail-interval-minminimum time between mail messages1h
propertiesjavamail properties in property file format
Example: Mail handler configuration
<web-app xmlns="http://caucho.com/ns/resin"
  xmlns:resin="urn:java:com.caucho.resin">

  <logger name="">
    <resin:MailLogHandler level="warning">
       <to>admin@foo.com</to>
       <properties>
         mail.smtp.host=127.0.0.1
         mail.smtp.port=25
       </properties>
    </resin:MailLogHandler>
  </logger>

</web-app>

SyslogHandler

On Unix systems, the SyslogHandler lets you log messages to syslog.

Example: syslog configuration
<resin xmlns="http://caucho.com/ns/resin"
      xmlns:resin="urn:java:com.caucho.resin">

<logger name="">
  <resin:SyslogHandler level="warning">
    <facility>daemon</facility>
    <severity>notice</severity>
  </resin:SyslogHandler>
</logger>

</resin>

The possible values for <facility> are user, mail, daemon, auth, lpr, news, uucp, cron, authpriv, ftp, local0, local1, local2, local3, local4, local5, local6, local7. The default is daemon.

The possible values for <severity> are emerg, alert, crit, err, warning, notice, info, debug. The default is info.

See also `man 3 syslog' and `man syslog.conf'.

Log rotation and archiving

Log rotation are a way stop your log files from getting too large, and to archive log files on a weekly or daily basis. When a rollover is triggered, the existing log file is renamed and a new file is started. Logs can be rotated by size or by time.

The same log rotation mechanism in Resin is used for JDK logging, HTTP access logging, and standard output logging.

Size based rollover

A size based rollover is triggered when the size of the file reaches a certain amount. The default Resin behaviour for log's is to rollover when the file size reaches 1mb.

rollover-size is used to specify the maximum size, and can be in bytes (50000), kilobytes (128kb), or megabytes (10mb). A value of -1 disables size based rollovers.

Time based rollover

A time based rollover is triggered when a certain period of time has passed since the last rollover. The default Resin behaviour is to perform no time based rollover, unless rollover-size has been disabled with a value of -1 in which case the default time period is 1 month.

rollover-period is used to specify the time period, and can be in days (15D), weeks (2W), months (1M), or hours (1h).

Archive files

When a rollover is triggered, the log file is renamed (archived) and a new log file is started.

archive-format is used to specify the name of the archive file. It can contain regular characters, EL Environment variables, and % codes that capture the current date and time. The % codes are the same as the ones used for timestamp (see Timestamp format string).

The default behaviour depends on the value of rollover-period. If rollover-period is greater than one day, or is not being used because rollover-size has been specified, the archive filename is the original path with .%Y%m%d appended. If rollover-period is less than one day, the archive filename is the original path with .%Y%m%d.%H appended.

Disabling rollovers

To completely disable rollovers, set the rollover-size to such a high number that it will never occur:

disable log rollovers
  <stdout-log path="log//stdout.log" rollover-size="1024mb"/>

Compression

Rollover log files can be compressed with gzip or zip. The extension of the archive-format determines the compression.

<log name="" level="warning" path='log/error.log'
     archive-format="%Y-%m-%d.error.log.gz"
     rollover-period="1D"/>

<access-log path="log/access.log"
            archive-format="access-%Y%m%d.log.gz"
            rollover-period="1D"/>

Standard Output Redirection

stdout-log

default use the JDK's destination for System.out

Configure the destination for System.out.

Usage of the <stdout-log> overrides a previous usage. For example, specifying <stdout-log> as a child of a <web-app> causes a redirection of System.out for that web application only, and will override the System.out location in the enclosing <host>.

Warning The path must not be the same as the path specified on the command line with -stdout. If it is, there will be conflicts with which process owns the file.
ATTRIBUTEDESCRIPTIONDEFAULT
archive-formatthe format for the archive filename when a rollover occurs, see Rollovers. see below
pathOutput path for the stream, see "Log Paths".required
path-formatSelects a format for generating path names. The syntax is the same as for archive-formatoptional
rollover-countmaximum number of rollover files before the oldest ones get overwritten. See Rollovers. none
rollover-periodhow often to rollover the log. Specify in days (15D), weeks (2W), months (1M), or hours (1h). See Rollovers. none
rollover-sizemaximum size of the file before a rollover occurs, in bytes (50000), kb (128kb), or megabytes (10mb). See Rollovers. 1mb
timestampa timestamp format string to use at the beginning of each log line.no timestamp

The default archive format is

path + ".%Y%m%d" or
  path + ".%Y%m%d.%H" if rollover-period < 1 day.

The following example configures System.out for a <host>. Unless a <web-app> overrides with it's own stdout-log, all web-apps in the host will write to the same output file.

...
<host id='foo.com'>
  <stdout-log path='/var/log/foo/stdout.log'
              rollover-period='1W'/>
  ...
</host>
...
  

stderr-log

default use the JDK's destination for System.err

Configure the destination for System.err.

Usage of the <stderr-log> overrides a previous usage. For example, specifying <stderr-log> as a child of a <web-app> causes a redirection of System.err for that web application only, and will override the System.err location in the enclosing <host>.

Warning The path must not be the same as the path specified on the command line with -stderr. If it is, there will be conflicts with which process owns the file.
ATTRIBUTEDESCRIPTIONDEFAULT
pathOutput path for the stream, see "Log Paths".required
path-formatSelects a format for generating path names. The syntax is the same as for archive-formatoptional
timestampa timestamp format string to use at the beginning of each log line.no timestamp
rollover-countmaximum number of rollover files before the oldest ones get overwritten. See Rollovers.none
rollover-periodhow often to rollover the log. Specify in days (15D), weeks (2W), months (1M), or hours (1h). See Rollovers.none
rollover-sizemaximum size of the file before a rollover occurs, in bytes (50000), kb (128kb), or megabytes (10mb). See Rollovers.1mb
archive-formatthe format for the archive filename when a rollover occurs, see Rollovers.see below

The default archive format is

path + ".%Y%m%d" or
  path + ".%Y%m%d.%H" if rollover-period < 1 day.

The following example configures System.err for a <host>. Unless a <web-app> overrides with it's own stderr-log, all web-apps in the host will write to the same output file.

...
<host id='foo.com'>
  <stderr-log path='/var/log/foo/stderr.log'
              rollover-period='1W'/>
  ...
</host>
...

<access-log>

<access-log> configures the access log file.

As a child of <web-app>, overrides the definition in the <host> that the web-app is deployed in. As a child of <host>, overrides the definition in the <server> that the host is in.

The default archive format is

path + ".%Y%m%d" or
  path + ".%Y%m%d.%H" if rollover-period < 1 day.

The access log formatting variables follow the Apache variables:

format patterns
PATTERNDESCRIPTION
%bresult content length
%Dtime taken to complete the request in microseconds (since 3.0.16)
%hremote IP addr
%{xxx}irequest header xxx
%{xxx}oresponse header xxx
%{xxx}ccookie value xxx
%{xxx}nrequest attribute
%{xxx}prequest parameter
%rrequest URL
%sstatus code
%Srequested session id
%{xxx}trequest date with optional time format string.
%Ttime taken to complete the request in seconds
%uremote user
%Urequest URI
%vname of the virtual host serving the request

The default format is:

default access log format
"%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\""

resin:type allows for custom logging. Applications can extend a custom class from com.caucho.http.log.AccessLog. Resin-IoC initialization can be used to set bean parameters in the custom class.

<access-log> Attributes
ATTRIBUTEDESCRIPTIONDEFAULT
pathOutput path for the log entries, see "Log Paths".required
path-formatSelects a format for generating path names. The syntax is the same as for archive-format.optional
archive-formatthe format for the archive filename when a rollover occurs, see Rollovers. see below
auto-flushtrue to flush the memory buffer with each request. false
auto-flush-timesets time interval for flushing the memory buffers 60s
excludeaccess logging exclude patterns for request URIs. Access to matching URIs does not get logged.none
formatAccess log format.see above
hostname-dns-lookuplog the dns name instead of the IP address (has a performance hit).false
rollover-periodhow often to rollover the log. Specify in days (15D), weeks (2W), months (1M), or hours (1h). See "Rollovers". none
rollover-sizemaximum size of the file before a rollover occurs, in bytes (50000), kb (128kb), or megabytes (10mb). See "Rollovers". 1gb
rollover-countmaximum number of rollover files before the oldest ones get overwritten. See "Rollovers". none
resin:typea class extending com.caucho.server.log.AccessLog for custom logging com.caucho.server.log.AccessLog
initResin-IoC initialization for the custom classn/a
<access-log> schema
element access-log {
  path?
  & path-format?
  & archive-format?
  $amp;auto-flush?
  & auto-flush-time?
  & exclude*
  & format?
  & hostname-dns-lookup?
  & rollover-period?
  & rollover-size?
  & rollover-count?
  & resin:type?
  & init?
}
Example: <access-log> in host configuration
<resin xmlns="http://caucho.com/ns/resin">
<cluster id="app-tier">

  <host id="">
    <access-log path='log/access.log'>
      <rollover-period>2W</rollover-period>
    </access-log>
  </host>
</cluster>
</resin>
Example: custom access log
<resin xmlns="http://caucho.com/ns/resin">

<cluster id="app-tier">

  <host id='foo.com'>

    <access-log>
      <test:MyLog xmlns:test="urn:java:test">
                 path='${resin.root}/foo/error.log'
                 rollover-period='1W'>
          <test:foo>bar</test:foo>
      </test:MyLog>
    </access-log>
    ...
  </host>

</cluster>
</resin>

Log Paths

path is used to configure a destination for the messages. Typically, <access-log>, <stdout-log>, and <stderr-log> are configured to go to files, and log is configured to go to a file or to stderr or stdout so that they show up on the console screen.

PATHRESULT
filesystem pathoutput log entries to a file
stdout:output log entries to stdout
stderr:output log entries to stderr
Log messages to stdout
  <log name="" level="all" path="stdout:"/>

You can use the Environment EL variables as part of your filesystem path:

Filesystem path using Environment EL variables
  <log name="" level="all" 
       path="log/debug-${server.id}.log"
       rollover-period="1h" rollover-count="1"/>

Copyright © 1998-2015 Caucho Technology, Inc. All rights reserved. Resin ® is a registered trademark. Quercustm, and Hessiantm are trademarks of Caucho Technology.