2 * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.checkstyle;
10 import com.google.common.base.Preconditions;
11 import com.google.common.io.Files;
12 import com.puppycrawl.tools.checkstyle.api.DetailAST;
14 import java.io.IOException;
15 import java.nio.charset.StandardCharsets;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
20 * Check which extracts the content of Logger messages somewhere (e.g. a file).
22 * <p>This can be used to create a comprehensive list of all log messages.
24 * <p>It is a first step towards more formal tracking of all messages
25 * from a system with a unique ID, using e.g. a framework such
28 * <p>Does not actually Check anything, i.e. never emits any Checkstyle warnings.
30 public class LogMessageExtractorCheck extends AbstractLogMessageCheck {
32 private static final Logger LOG = LoggerFactory.getLogger(LogMessageExtractorCheck.class);
34 static final File DEFAULT_REPORT_FILE = new File("target/logger-messages.txt");
36 private File logMessagesReportFile = DEFAULT_REPORT_FILE;
38 public void setLogMessagesReportFileName(String fileName) {
39 logMessagesReportFile = new File(fileName);
40 logMessagesReportFile.getParentFile().mkdirs();
43 public File getLogMessagesReportFile() {
44 return logMessagesReportFile;
48 protected void visitLogMessage(DetailAST ast, String logMessage) {
49 File file = new File(getFileContents().getFileName());
50 String fileName = FileNameUtil.getPathRelativeToMavenProjectRootIfPossible(file).getPath();
51 int lineNumber = ast.getLineNo();
52 LogMessageOccurence log = new LogMessageOccurence(fileName, lineNumber, logMessage);
53 updateMessagesReportFile(log);
56 protected void updateMessagesReportFile(LogMessageOccurence log) {
58 final File file = getLogMessagesReportFile();
60 Files.append(log.toString() + "\n", file, StandardCharsets.UTF_8);
62 Files.write(log.toString() + "\n", file, StandardCharsets.UTF_8);
64 } catch (IOException e) {
65 LOG.error("Failed to append to file: {}", logMessagesReportFile.getPath(), e);
69 public static class LogMessageOccurence {
71 // relative to current project root
72 public final String javaSourceFilePath;
73 public final int lineNumber;
74 public final String message;
76 public LogMessageOccurence(String javaSourceFilePath, int lineNumber, String message) {
77 this.javaSourceFilePath = Preconditions.checkNotNull(javaSourceFilePath, "javaSourceFilePath");
78 this.lineNumber = lineNumber;
79 this.message = Preconditions.checkNotNull(message, "message");
83 public String toString() {
84 return javaSourceFilePath + ":" + lineNumber + ":" + message;