猿问

在 Java 记录器中,如何添加检查以查看它们是否输出某个日志级别的代码

我正在制作一个使用我构建的自定义库的程序。他们都在使用 Java util 日志记录类并制作日志文件。如果使用警告级别制作日志,我想要代码将布尔值设置为 true。除了扫描日志文件寻找警告评论,我还能做些什么来实现这一目标?


慕斯709654
浏览 162回答 2
2回答

函数式编程

我不会尝试分析日志文件,而是将库实现更改为执行以下操作:class Parser {&nbsp; &nbsp; private List<String> warnings = new ArrayList<>();&nbsp; &nbsp; public Boolean hasWarnings() {&nbsp; &nbsp; &nbsp; &nbsp; return warnings.size() > 0&nbsp; &nbsp; }&nbsp; &nbsp; public List<String> getWarnings() {&nbsp; &nbsp; &nbsp; &nbsp; return warnings;&nbsp; &nbsp; }&nbsp; &nbsp; public Object parse(String xml) {&nbsp; &nbsp; &nbsp; &nbsp; // parse the xml&nbsp; &nbsp; &nbsp; &nbsp; if (needToIssueWarning) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String msg = "warning!";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; warnings.add(msg);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; logger.warn(msg);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return parsedData;&nbsp; &nbsp; }}并在呼叫站点:private void run() {&nbsp; &nbsp; Parser parser = new Parser();&nbsp; &nbsp; parsedData = parse(xmlString);&nbsp; &nbsp; if (parser.hasWarnings()) {&nbsp; &nbsp; &nbsp; &nbsp; warnings = parser.getWarnings();&nbsp; &nbsp; &nbsp; &nbsp; //do something with the warnings&nbsp; &nbsp; }}如果您要寻找解析日志的解决方案,则无法保证日志级别包含警告,它可能会设置为错误,然后您会错过消息

白衣染霜花

创建查找WARNING级别消息的java.util.logging.Filter。在根记录器的处理程序上安装该过滤器。public class WarningFilter implements Filter {&nbsp; &nbsp; @Override&nbsp; &nbsp; public boolean isLoggable(LogRecord record) {&nbsp; &nbsp; &nbsp; &nbsp; if (Level.WARNING.equals(record.getLevel())) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//Set your boolean.&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return true; //Allow all records to pass.&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答