You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行Java程序打印控制台日志如何避免Fortify不良日志实践报错

问题根因

Fortify扫描触发「Poor Logging Practice: Use of a System Output Stream」报错的核心原因是System.out/System.err属于裸写控制台输出,无法统一管控日志级别、格式化、持久化存储,不符合工业级Java开发的日志规范。

可替代实现方案

方案1:SLF4J日志门面 + 日志实现(生产/通用场景首选)

SLF4J是Java生态通用的日志标准,搭配Logback/Log4j2实现即可满足日志输出需求,可灵活配置输出路径、格式、级别,完全符合开发规范,不会触发扫描报错。

操作步骤

  1. 项目中引入依赖(Maven示例):
<!-- SLF4J API -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>2.0.9</version>
</dependency>
<!-- Logback 实现,无需额外配置默认输出到控制台 -->
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.4.11</version>
</dependency>
  1. 代码中定义日志实例,替换System.out.println:
    在类中定义全局Logger实例:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// 替换为你自己的类名
private static final Logger logger = LoggerFactory.getLogger(YourClassName.class);

把原来的System.out.println替换为logger.info()即可。

方案2:测试框架自带日志工具(当前自动化测试场景首选)

你提供的代码是Selenium自动化测试用例,可直接使用测试框架自带的日志输出能力,无需额外引入依赖,输出内容还会同步到测试报告中:

  • 若使用TestNG框架:直接调用org.testng.Reporter.log("日志内容")
  • 若使用JUnit5框架:注入TestReporter实例调用reportEntry("日志内容")

方案3:JDK自带java.util.logging(无外部依赖场景可选)

如果不想引入第三方依赖,可直接使用JDK内置的日志工具,也符合规范:

import java.util.logging.Logger;

private static final Logger logger = Logger.getLogger(YourClassName.class.getName());
// 输出日志
logger.info("日志内容");
改造后的代码示例(SLF4J版本)
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.openqa.selenium.By;
import org.testng.Assert;
// 其他已有import保持不变

public class YourTestClass {
    // 初始化日志实例
    private static final Logger logger = LoggerFactory.getLogger(YourTestClass.class);

    public static void IBanUpdateTest(){   
        driver.get("http://10.10.10.10/demo-web-1.0-SNAPSHOT"); //define the url
        String pageTitle = driver.getTitle();       //get the title of the webpage
        logger.info("The title of this page is ===> {}", pageTitle);
        Assert.assertEquals("IBan - Business ID code", pageTitle);    //verify the title of the webpage
        driver.findElement(By.id("0iban")).clear();//clear the input field before entering any value
        driver.findElement(By.id("0iban")).sendKeys("5464564654");//enter the IBan Value
        driver.findElement(By.id("0businessIdentifierCode")).clear();
        driver.findElement(By.id("0businessIdentifierCode")).sendKeys("54645646548546465"); //enter the BIC value 
        driver.findElement(By.id("0updateRow")).click();      //click Update button
        logger.info("Successfully updated the row");
    }
}

注:使用{}占位符输出变量比字符串拼接性能更高,是日志框架的推荐写法。

内容的提问来源于stack exchange,提问作者user630702

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 06:09:03