Skip to content

Commit

Permalink
#318 Explicitly set logger for CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
ascheman committed Jan 24, 2025
1 parent 0678302 commit 5989fe8
Show file tree
Hide file tree
Showing 4 changed files with 96 additions and 34 deletions.
4 changes: 1 addition & 3 deletions htmlSanityCheck-cli/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ dependencies {

implementation platform("org.codehaus.groovy:groovy-bom:${GroovySystem.version}")
implementation 'org.codehaus.groovy:groovy'
implementation 'org.slf4j:slf4j-api'
implementation 'org.slf4j:slf4j-log4j12'
// implementation 'ch.qos.logback:logback-classic:1.2.11'
implementation 'org.slf4j:slf4j-jdk14'

implementation project(":htmlSanityCheck-core")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,20 @@ import org.aim42.htmlsanitycheck.AllChecksRunner
import org.aim42.htmlsanitycheck.Configuration
import org.aim42.htmlsanitycheck.ProductInformation
import org.aim42.htmlsanitycheck.check.AllCheckers
import org.apache.log4j.Level
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import picocli.CommandLine
import picocli.CommandLine.Command
import picocli.CommandLine.Option
import picocli.CommandLine.Parameters

import java.nio.file.Files
import java.nio.file.Paths
import java.util.logging.Formatter
import java.util.logging.ConsoleHandler
import java.util.logging.Level
import java.util.logging.LogManager
import java.util.logging.LogRecord
import java.util.logging.Logger
import java.util.logging.SimpleFormatter

// see end-of-file for license information

Expand All @@ -22,7 +26,44 @@ import java.nio.file.Paths
showDefaultValues = true
)
class HscCommand implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(HscCommand.class)
private static final Logger rootLogger
private static ConsoleHandler consoleHandler

private static final Logger logger

private static final String SHORT_FORMAT = "%1\$s%n"
private static final String LEVEL_FORMAT = "%2\$-7s - %1\$s%n"
private static final String LEVEL_CLASS_FORMAT = "%2\$-7s - %3\$s - %1\$s%n"

private static void setLogFormatter(final String format) {
Formatter formatter = new SimpleFormatter() {

@Override
synchronized String format(LogRecord lr) {
return String.format(format,
lr.getMessage(),
lr.getLevel().getLocalizedName(),
String.format("%-30s", lr.getSourceClassName())
)
}
}
consoleHandler.setFormatter(formatter)
}

static {
LogManager logManager = LogManager.getLogManager();
logManager.reset();

rootLogger = Logger.getLogger("org.aim42.htmlsanitycheck")
logger = Logger.getLogger(HscCommand.class.name)

rootLogger.setLevel(Level.WARNING)
consoleHandler = new ConsoleHandler()

setLogFormatter(SHORT_FORMAT)

rootLogger.addHandler(consoleHandler)
}

HscRunner runner

Expand All @@ -33,7 +74,7 @@ class HscCommand implements Runnable {
@Option(names = ["-v", "--verbose"],
description = "Increase verbosity. Repeatable, cumulative -v -vv -vvv",
fallbackValue = "true", arity = "0..3")
private boolean[] verbosity;
private boolean[] verbosity

@Option(names = ["-V", "--version"], description = "Display version information")
boolean versionRequested
Expand Down Expand Up @@ -77,39 +118,43 @@ class HscCommand implements Runnable {
CommandLine cmd

private static void setLogLevel(final Level level) {
org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("org.aim42.htmlsanitycheck"
);
logger.setLevel(level);
rootLogger.setLevel(level)
consoleHandler.setLevel(level)
}

private void configureLogging() {
if (hscCommand.verbosity != null) {
int verbosityLevel = hscCommand.verbosity.length;
int verbosityLevel = hscCommand.verbosity.length
switch (verbosityLevel) {
case 0:
// Default logging level
break;
break
case 1:
setLogLevel(Level.INFO);
break;
setLogLevel(Level.INFO)
break
case 2:
setLogLevel(Level.DEBUG);
break;
setLogLevel(Level.FINE)
setLogFormatter(LEVEL_FORMAT)
break
case 3:
default:
setLogLevel(Level.TRACE);
break;
setLogLevel(Level.FINER)
setLogFormatter(LEVEL_CLASS_FORMAT)
break
case 4:
setLogLevel(Level.FINEST)
setLogFormatter(LEVEL_CLASS_FORMAT)
break
}
}
}

void run() {
configureLogging();
if (hscCommand.versionRequested) {
System.out.println("Version: ${ProductInformation.VERSION}")
return
}

configureLogging()
def srcDocuments = hscCommand.srcDocs ?: hscCommand.findFiles()
if (!srcDocuments) {
System.err.println("Please specify at least one src document (either explicitly or implicitly)")
Expand All @@ -128,15 +173,14 @@ class HscCommand implements Runnable {
// if we have no valid configuration, abort with exception
configuration.validate()
logger.fine("Starting HTML sanity check")
logger.info("Starting HTML sanity check");
// create output directory for checking results
resultsDirectory.mkdirs()
// create output directory for checking results
resultsDirectory.mkdirs()

// create an AllChecksRunner...
var allChecksRunner = new AllChecksRunner(configuration)

// ... and perform the actual checks
var allChecks = allChecksRunner.performAllChecks()
var allChecks = allChecksRunner.performAllChecks(false)

// check for findings and fail build if requested
var nrOfFindingsOnAllPages = allChecks.nrOfFindingsOnAllPages()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ class HscCommandSpec extends Specification {

@Rule
TemporaryFolder testProjectDir = new TemporaryFolder()
@Rule
TemporaryFolder testResultsDir = new TemporaryFolder()

File htmlFile
ByteArrayOutputStream outContent
ByteArrayOutputStream errContent
Expand Down Expand Up @@ -94,14 +97,31 @@ class HscCommandSpec extends Specification {
def "test with valid HTML file"() {
given:
htmlFile << VALID_HTML
String[] args = [testProjectDir.root]
String[] args = ["-r", testResultsDir.root, testProjectDir.root]

when:
HscCommand.main(args)

then:
outContent.toString().contains("found 0 issue, 100% successful.")
File resultFile = new File (testResultsDir.root, 'index.html')
resultFile.exists()
String result = resultFile.text
result.toString().contains("<div class=\"infoBox success\" id=\"successRate\"><div class=\"percent\">100%</div>successful</div>")
}

def "test with invalid HTML file"() {
given:
htmlFile << INVALID_HTML
String[] args = ["-r", testResultsDir.root, testProjectDir.root]

when:
HscCommand.main(args)

then:
File resultFile = new File (testResultsDir.root, 'index.html')
resultFile.exists()
String result = resultFile.text
result.toString().contains("<div class=\"infoBox failures\" id=\"successRate\"><div class=\"percent\">0%</div>successful</div>\n")
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,11 @@ public AllChecksRunner(Configuration configuration) {
* Performs all available checks on pageToCheck
*/
public PerRunResults performAllChecks() throws IOException {
return performAllChecks(true);
}

logger.debug("entered performAllChecks");
public PerRunResults performAllChecks(boolean useConsoleReporter) throws IOException {
logger.debug("entered performAllChecks ({})", useConsoleReporter);

for (File file : filesToCheck) {
resultsForAllPages.addPageResults(
Expand All @@ -96,7 +99,9 @@ public PerRunResults performAllChecks() throws IOException {
// and then report the results
reportCheckingResultsOnLogger();
/* Determines if the report is output to the console. */
reportCheckingResultsOnConsole();
if (useConsoleReporter) {
reportCheckingResultsOnConsole();
}
if (checkingResultsDir != null) {
reportCheckingResultsAsHTML(checkingResultsDir.getAbsolutePath());
}
Expand Down Expand Up @@ -147,7 +152,6 @@ private void reportCheckingResultsOnConsole() {
Reporter reporter = new ConsoleReporter(resultsForAllPages);

reporter.reportFindings();

}

/**
Expand All @@ -156,16 +160,13 @@ private void reportCheckingResultsOnConsole() {
*/
private void reportCheckingResultsOnLogger() {
Reporter reporter = new LoggerReporter(resultsForAllPages, logger);

reporter.reportFindings();

}

/**
* Report results in HTML file(s)
*/
private void reportCheckingResultsAsHTML(String resultsDir) {

Reporter reporter = new HtmlReporter(resultsForAllPages, resultsDir);
reporter.reportFindings();
}
Expand All @@ -174,7 +175,6 @@ private void reportCheckingResultsAsHTML(String resultsDir) {
* Report results in JUnit XML
*/
private void reportCheckingResultsAsJUnitXml(String resultsDir) {

Reporter reporter = new JUnitXmlReporter(resultsForAllPages, resultsDir);
reporter.reportFindings();
}
Expand Down

0 comments on commit 5989fe8

Please sign in to comment.