tomcat4的日志记录器相关代码示例《how tomcat works》

作者: admin 分类: Tomcat 发布时间: 2019-11-20 14:09  阅读: 46 views

日志记录器是用来记录消息的组件。在Catalina中,日志记录器需要与某个servlet容器相关联。与其他组件比较,相对简单一些。

Tomcat中的日志记录器都必须实现org.apache.catalina.Logger接口,如下:

package org.apache.catalina;

import java.beans.PropertyChangeListener;

public abstract interface Logger
{
  public static final int FATAL = Integer.MIN_VALUE;
  public static final int ERROR = 1;
  public static final int WARNING = 2;
  public static final int INFORMATION = 3;
  public static final int DEBUG = 4;

  public abstract Container getContainer();

  public abstract void setContainer(Container paramContainer);

  public abstract String getInfo();

  public abstract int getVerbosity();

  public abstract void setVerbosity(int paramInt);

  public abstract void addPropertyChangeListener(PropertyChangeListener paramPropertyChangeListener);

  public abstract void log(String paramString);

  public abstract void log(Exception paramException, String paramString);

  public abstract void log(String paramString, Throwable paramThrowable);

  public abstract void log(String paramString, int paramInt);

  public abstract void log(String paramString, Throwable paramThrowable, int paramInt);

  public abstract void removePropertyChangeListener(PropertyChangeListener paramPropertyChangeListener);
}

Tomcat4x提供了三种日志记录器,其类分别是FileLogger、SystemErrorLogger和SystemOutLogger,位于org.apache.catalina.logger包下,均继承自org.apache.catalina.logger.LoggerBase类。Tomcat5X的LoggerBase还实现了Lifecycle接口等。

LoggerBase类是一个抽象类,实现了Logger接口中除了log(String msg)方法(抽象方法)外的全部方法实现。需要子类实现的方法签名如下:

public abstract void log(String msg);

该方法在子类中给出具体的实现,并有多种重载方法,所有的重载log()方法最终都会调用该方法。LoggerBase类通过设置一个名为verbosity的变量来设置日志等级。

package org.apache.catalina.logger;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import org.apache.catalina.Container;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Logger;

public abstract class LoggerBase
  implements Logger
{
  protected Container container = null;
  protected int debug = 0;
  protected static final String info = "org.apache.catalina.logger.LoggerBase/1.0";
  protected PropertyChangeSupport support = new PropertyChangeSupport(this);
  protected int verbosity = 1;

  public Container getContainer()
  {
    return this.container;
  }

  public void setContainer(Container container)
  {
    Container oldContainer = this.container;
    this.container = container;
    this.support.firePropertyChange("container", oldContainer, this.container);
  }

  public int getDebug()
  {
    return this.debug;
  }

  public void setDebug(int debug)
  {
    this.debug = debug;
  }

  public String getInfo()
  {
    return "org.apache.catalina.logger.LoggerBase/1.0";
  }

  public int getVerbosity()
  {
    return this.verbosity;
  }

  public void setVerbosity(int verbosity)
  {
    this.verbosity = verbosity;
  }

  public void setVerbosityLevel(String verbosity)
  {
    if ("FATAL".equalsIgnoreCase(verbosity)) {
      this.verbosity = Integer.MIN_VALUE;
    } else if ("ERROR".equalsIgnoreCase(verbosity)) {
      this.verbosity = 1;
    } else if ("WARNING".equalsIgnoreCase(verbosity)) {
      this.verbosity = 2;
    } else if ("INFORMATION".equalsIgnoreCase(verbosity)) {
      this.verbosity = 3;
    } else if ("DEBUG".equalsIgnoreCase(verbosity)) {
      this.verbosity = 4;
    }
  }

  public void addPropertyChangeListener(PropertyChangeListener listener)
  {
    this.support.addPropertyChangeListener(listener);
  }

  public abstract void log(String paramString);

  public void log(Exception exception, String msg)
  {
    log(msg, exception);
  }

  public void log(String msg, Throwable throwable)
  {
    CharArrayWriter buf = new CharArrayWriter();
    PrintWriter writer = new PrintWriter(buf);
    writer.println(msg);
    throwable.printStackTrace(writer);
    Throwable rootCause = null;
    if ((throwable instanceof LifecycleException)) {
      rootCause = ((LifecycleException)throwable).getThrowable();
    } else if ((throwable instanceof ServletException)) {
      rootCause = ((ServletException)throwable).getRootCause();
    }
    if (rootCause != null)
    {
      writer.println("----- Root Cause -----");
      rootCause.printStackTrace(writer);
    }
    log(buf.toString());
  }

  public void log(String message, int verbosity)
  {
    if (this.verbosity >= verbosity) {
      log(message);
    }
  }

  public void log(String message, Throwable throwable, int verbosity)
  {
    if (this.verbosity >= verbosity) {
      log(message, throwable);
    }
  }

  public void removePropertyChangeListener(PropertyChangeListener listener)
  {
    this.support.removePropertyChangeListener(listener);
  }
}

接下来看下LoggerBase的三个子类,

SystemOutLogger.java(输出日志)

package org.apache.catalina.logger;

import java.io.PrintStream;

public class SystemOutLogger
  extends LoggerBase
{
  protected static final String info = "org.apache.catalina.logger.SystemOutLogger/1.0";

  public void log(String msg)
  {
    System.out.println(msg);
  }
}

SystemOutLogger.java(输出错误日志)

package org.apache.catalina.logger;

import java.io.PrintStream;

public class SystemErrLogger
  extends LoggerBase
{
  protected static final String info = "org.apache.catalina.logger.SystemErrLogger/1.0";

  public void log(String msg)
  {
    System.err.println(msg);
  }
}

FileLogger.java(将日志记录到文件中,并设置文件的各种配置)

package org.apache.catalina.logger;

import java.beans.PropertyChangeSupport;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.util.LifecycleSupport;
import org.apache.catalina.util.StringManager;

public class FileLogger
  extends LoggerBase
  implements Lifecycle
{
  private String date = "";
  private String directory = "logs";
  protected static final String info = "org.apache.catalina.logger.FileLogger/1.0";
  protected LifecycleSupport lifecycle = new LifecycleSupport(this);
  private String prefix = "catalina.";
  private StringManager sm = StringManager.getManager("org.apache.catalina.logger");
  private boolean started = false;
  private String suffix = ".log";
  private boolean timestamp = false;
  private PrintWriter writer = null;

  public String getDirectory()
  {
    return this.directory;
  }

  public void setDirectory(String directory)
  {
    String oldDirectory = this.directory;
    this.directory = directory;
    this.support.firePropertyChange("directory", oldDirectory, this.directory);
  }

  public String getPrefix()
  {
    return this.prefix;
  }

  public void setPrefix(String prefix)
  {
    String oldPrefix = this.prefix;
    this.prefix = prefix;
    this.support.firePropertyChange("prefix", oldPrefix, this.prefix);
  }

  public String getSuffix()
  {
    return this.suffix;
  }

  public void setSuffix(String suffix)
  {
    String oldSuffix = this.suffix;
    this.suffix = suffix;
    this.support.firePropertyChange("suffix", oldSuffix, this.suffix);
  }

  public boolean getTimestamp()
  {
    return this.timestamp;
  }

  public void setTimestamp(boolean timestamp)
  {
    boolean oldTimestamp = this.timestamp;
    this.timestamp = timestamp;
    this.support.firePropertyChange("timestamp", new Boolean(oldTimestamp), new Boolean(this.timestamp));
  }

  public void log(String msg)
  {
    Timestamp ts = new Timestamp(System.currentTimeMillis());
    String tsString = ts.toString().substring(0, 19);
    String tsDate = tsString.substring(0, 10);
    if (!this.date.equals(tsDate)) {
      synchronized (this)
      {
        if (!this.date.equals(tsDate))
        {
          close();
          this.date = tsDate;
          open();
        }
      }
    }
    if (this.writer != null) {
      if (this.timestamp) {
        this.writer.println(tsString + " " + msg);
      } else {
        this.writer.println(msg);
      }
    }
  }

  private void close()
  {
    if (this.writer == null) {
      return;
    }
    this.writer.flush();
    this.writer.close();
    this.writer = null;
    this.date = "";
  }

  private void open()
  {
    File dir = new File(this.directory);
    if (!dir.isAbsolute()) {
      dir = new File(System.getProperty("catalina.base"), this.directory);
    }
    dir.mkdirs();
    try
    {
      String pathname = dir.getAbsolutePath() + File.separator + this.prefix + this.date + this.suffix;

      this.writer = new PrintWriter(new FileWriter(pathname, true), true);
    }
    catch (IOException e)
    {
      this.writer = null;
    }
  }

  public void addLifecycleListener(LifecycleListener listener)
  {
    this.lifecycle.addLifecycleListener(listener);
  }

  public LifecycleListener[] findLifecycleListeners()
  {
    return this.lifecycle.findLifecycleListeners();
  }

  public void removeLifecycleListener(LifecycleListener listener)
  {
    this.lifecycle.removeLifecycleListener(listener);
  }

  public void start()
    throws LifecycleException
  {
    if (this.started) {
      throw new LifecycleException(this.sm.getString("fileLogger.alreadyStarted"));
    }
    this.lifecycle.fireLifecycleEvent("start", null);
    this.started = true;
  }

  public void stop()
    throws LifecycleException
  {
    if (!this.started) {
      throw new LifecycleException(this.sm.getString("fileLogger.notStarted"));
    }
    this.lifecycle.fireLifecycleEvent("stop", null);
    this.started = false;

    close();
  }
}

上面几个类的关系如下
log

最后在启动器调用日志记录器时,编码如下;

// ------ add logger --------
System.setProperty("catalina.base", System.getProperty("user.dir"));
FileLogger logger = new FileLogger();
logger.setPrefix("FileLog_");
logger.setSuffix(".txt");
logger.setTimestamp(true);
logger.setDirectory("webroot");
context.setLogger(logger);


   原创文章,转载请标明本文链接: tomcat4的日志记录器相关代码示例《how tomcat works》

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表评论

电子邮件地址不会被公开。 必填项已用*标注

更多阅读