如何定义其他Java日志级别?

时间:2013-02-28 09:37:05

标签: java logging syslog

standard Java logging定义了以下日志级别:

  • 严重(最高)
  • 警告
  • INFO
  • CONFIG
  • FINE
  • FINER
  • FINEST

这与RFC 5424不兼容,因为它在INFO和WARNING之间缺少NOTICE级别。 Java缺少一些额外的日志级别(错误,严重,警报和紧急情况)但是NOTICE会伤害我。

有没有办法扩展可能的日志级别列表以添加缺少的NOTICE级别?或者是否有必要重写整个日志记录?

3 个答案:

答案 0 :(得分:2)

这应该有效

class Level2 extends Level {
    public static final Level2 NOTICE = new Level2("NOTICE", 850);

    private Level2(String name, int level) {
        super(name, level);
    }
}

答案 1 :(得分:2)

感谢Evgeniy。这是一个完整的例子:

<强> SyslogLevel

import java.util.logging.Level;

public class SyslogLevel extends Level
{
    public static SyslogLevel EMERG   = new SyslogLevel("EMERG",   1100);
    public static SyslogLevel ALERT   = new SyslogLevel("ALERT",   1000);
    public static SyslogLevel ERR     = new SyslogLevel("ERR",     950);
    public static SyslogLevel WARNING = new SyslogLevel("WARNING", 900);
    public static SyslogLevel NOTICE  = new SyslogLevel("NOTICE",  850);
    public static SyslogLevel INFO    = new SyslogLevel("INFO",    800);
    public static SyslogLevel DEBUG   = new SyslogLevel("DEBUG",   300);

    protected SyslogLevel (String name, int value, String resourceBundleName)
    {
        super (name, value, resourceBundleName);
    }

    protected SyslogLevel (String name, int value)
    {
        super (name, value);
    }
}

<强>登录

import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.logging.FileHandler;
import java.util.logging.SimpleFormatter;

public class logging
{
    public static void main(String[] args)
    {
        Logger logger = Logger.getLogger ("MyLog");
        FileHandler fh;
        try {
            fh = new FileHandler ("logging.log", true);
            logger.addHandler (fh);
            logger.setLevel (Level.ALL);
            fh.setFormatter (new SimpleFormatter());
            logger.log (SyslogLevel.NOTICE, "Run!");
        }
        catch (java.io.IOException e) {
            e.printStackTrace ();
        }
    }
}

答案 2 :(得分:1)

您可以扩展Level class并提供更多功能。