如何配置logging.properties将内容抛入Java类(没有包装模式)?

时间:2013-02-19 18:31:14

标签: java logging

我的tomcat / conf目录中有一个常见的logging.properties ..

如何修改它以便能够处理(使用java类)我的应用程序生成的所有日志?

有没有办法在不使用包装器(来自Log API)类的情况下执行此操作?

1 个答案:

答案 0 :(得分:0)

您可以使用Handler子类来处理正在记录的数据。

然后,您可以通过配置文件或programmaticaly通过Logger类的addHandler方法将其添加到根记录器。

例如,您可以创建一个Handler子类FoobarHandler,它在控制台上打印所有记录的数据,前缀为“Foobar”文本:

public class MyHandler extends Handler {

    @Override
    public void close() throws SecurityException {
        // housekeeping before handler close
    }

    @Override
    public void flush() {
        // not really needed as data is processed without any sort of buffering
    }

    @Override
    public void publish(LogRecord record) {
        System.out.println("Foobar " + record.getMessage().toUpperCase());
    }

}

在配置文件中,将Handler的类名称(即myapp.FoobarHandler)添加到全局处理程序配置中:

# Global logging properties.
# ------------------------------------------
# The set of handlers to be loaded upon startup.
# Comma-separated list of class names.
# (? LogManager docs say no comma here, but JDK example has comma.)
handlers=java.util.logging.FileHandler, myapp.FoobarHandler

# Default global logging level.
# Loggers and Handlers may override this level
.level=INFO

# Loggers
# ------------------------------------------
# Loggers are usually attached to packages.
# Here, the level for each package is specified.
# The global level is used by default, so levels
# specified here simply act as an override.
myapp.ui.level=ALL
myapp.business.level=CONFIG
myapp.data.level=SEVERE