Browse Source

slf4j support and logging #29

Jhonny Mertz 7 years ago
parent
commit
ef07e0b1a5

+ 14 - 1
pom.xml

@@ -3,7 +3,7 @@
     <modelVersion>4.0.0</modelVersion>
     <groupId>com.github.jhonnymertz</groupId>
     <artifactId>java-wkhtmltopdf-wrapper</artifactId>
-    <version>1.1.1-RELEASE</version>
+    <version>1.1.2-RELEASE</version>
 
     <dependencies>
 
@@ -33,6 +33,19 @@
             <version>2.5</version>
         </dependency>
 
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-api</artifactId>
+            <version>1.7.25</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-simple</artifactId>
+            <version>1.7.5</version>
+            <scope>test</scope>
+        </dependency>
+
     </dependencies>
 
 </project>

+ 18 - 2
src/main/java/com/github/jhonnymertz/wkhtmltopdf/wrapper/Pdf.java

@@ -8,11 +8,14 @@ import com.github.jhonnymertz.wkhtmltopdf.wrapper.params.Params;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
 import java.util.UUID;
 import java.util.concurrent.*;
@@ -22,6 +25,8 @@ import java.util.concurrent.*;
  */
 public class Pdf {
 
+    private static final Logger logger = LoggerFactory.getLogger(Pdf.class);
+
     private static final String STDINOUT = "-";
 
     private final WrapperConfig wrapperConfig;
@@ -43,6 +48,7 @@ public class Pdf {
         this.params = new Params();
         this.tocParams = new Params();
         this.pages = new ArrayList<Page>();
+        logger.info("Initialized with {}", wrapperConfig);
     }
 
     /**
@@ -91,6 +97,7 @@ public class Pdf {
     public File saveAs(String path) throws IOException, InterruptedException {
         File file = new File(path);
         FileUtils.writeByteArrayToFile(file, getPDF());
+        logger.info("PDF successfully saved in {}", file.getAbsolutePath());
         return file;
     }
 
@@ -99,19 +106,27 @@ public class Pdf {
         ExecutorService executor = Executors.newFixedThreadPool(2);
 
         try {
+            logger.debug("Generating pdf with: {}", getCommand());
             Process process = Runtime.getRuntime().exec(getCommandAsArray());
 
             Future<byte[]> inputStreamToByteArray = executor.submit(streamToByteArrayTask(process.getInputStream()));
-            Future<byte[]> errorStreamToByteArray = executor.submit(streamToByteArrayTask(process.getErrorStream()));
+            Future<byte[]> outputStreamToByteArray = executor.submit(streamToByteArrayTask(process.getErrorStream()));
 
             process.waitFor();
 
             if (process.exitValue() != 0) {
-                throw new RuntimeException("Process (" + getCommand() + ") exited with status code " + process.exitValue() + ":\n" + new String(getFuture(errorStreamToByteArray)));
+                byte[] errorStream = getFuture(outputStreamToByteArray);
+                logger.error("Error while generating pdf: {}", new String(errorStream));
+                throw new RuntimeException("Process (" + getCommand() + ") exited with status code " + process.exitValue() + ":\n" + new String(errorStream));
+            }
+            else{
+                logger.debug("Wkhtmltopdf output:\n{}", new String(getFuture(outputStreamToByteArray)));
             }
 
+            logger.info("PDF successfully generated with: {}", getCommand());
             return getFuture(inputStreamToByteArray);
         } finally {
+            logger.debug("Shutting down executor for wkhtmltopdf.");
             executor.shutdownNow();
             cleanTempFiles();
         }
@@ -165,6 +180,7 @@ public class Pdf {
     }
 
     private void cleanTempFiles() {
+        logger.debug("Cleaning up temporary files...");
         for (Page page : pages) {
             if (page.getType().equals(PageType.htmlAsString)) {
                 new File(page.getSource()).delete();

+ 17 - 2
src/main/java/com/github/jhonnymertz/wkhtmltopdf/wrapper/configurations/WrapperConfig.java

@@ -3,15 +3,20 @@ package com.github.jhonnymertz.wkhtmltopdf.wrapper.configurations;
 import java.io.IOException;
 import java.nio.charset.Charset;
 import org.apache.commons.io.IOUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class WrapperConfig {
 
+    private static final Logger logger = LoggerFactory.getLogger(WrapperConfig.class);
+
     private XvfbConfig xvfbConfig;
 
     private String wkhtmltopdfCommand = "wkhtmltopdf";
 
     public WrapperConfig() {
-      setWkhtmltopdfCommand(findExecutable());
+        logger.debug("Initialized with default configurations.");
+        setWkhtmltopdfCommand(findExecutable());
     }
 
     public WrapperConfig(String wkhtmltopdfCommand) {
@@ -43,8 +48,10 @@ public class WrapperConfig {
             String text = IOUtils.toString(p.getInputStream(), Charset.defaultCharset()).trim();
 
             if (text.isEmpty())
-                throw new RuntimeException();
+                throw new RuntimeException("wkhtmltopdf command was not found in your classpath. " +
+                        "Verify its installation or initialize wrapper configurations with correct path/to/wkhtmltopdf");
 
+            logger.debug("Wkhtmltopdf command found in classpath: {}", text);
             setWkhtmltopdfCommand(text);
         } catch (InterruptedException e) {
             e.printStackTrace();
@@ -68,4 +75,12 @@ public class WrapperConfig {
     public void setXvfbConfig(XvfbConfig xvfbConfig) {
         this.xvfbConfig = xvfbConfig;
     }
+
+    @Override
+    public String toString() {
+        return "{" +
+                "xvfbConfig=" + xvfbConfig +
+                ", wkhtmltopdfCommand='" + wkhtmltopdfCommand + '\'' +
+                '}';
+    }
 }

+ 7 - 0
src/main/java/com/github/jhonnymertz/wkhtmltopdf/wrapper/configurations/XvfbConfig.java

@@ -40,4 +40,11 @@ public class XvfbConfig {
         return commandLine;
     }
 
+    @Override
+    public String toString() {
+        return "{" +
+                "command='" + command + '\'' +
+                ", params=" + params +
+                '}';
+    }
 }

+ 4 - 1
src/test/java/com/github/jhonnymertz/wkhtmltopdf/wrapper/PdfTest.java

@@ -96,6 +96,9 @@ public class PdfTest {
         // that is a valid PDF (otherwise an IOException occurs)
         parser.parse();
         PDFTextStripper pdfTextStripper = new PDFTextStripper();
-        return pdfTextStripper.getText(new PDDocument(parser.getDocument()));
+        PDDocument pdDocument = new PDDocument(parser.getDocument());
+        String text = pdfTextStripper.getText(pdDocument);
+        pdDocument.close();
+        return text;
     }
 }

+ 34 - 0
src/test/resources/simplelogger.properties

@@ -0,0 +1,34 @@
+# SLF4J's SimpleLogger configuration file
+# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.
+
+# Default logging detail level for all instances of SimpleLogger.
+# Must be one of ("trace", "debug", "info", "warn", or "error").
+# If not specified, defaults to "info".
+org.slf4j.simpleLogger.defaultLogLevel=debug
+
+# Logging detail level for a SimpleLogger instance named "xxxxx".
+# Must be one of ("trace", "debug", "info", "warn", or "error").
+# If not specified, the default logging detail level is used.
+#org.slf4j.simpleLogger.log.xxxxx=
+
+# Set to true if you want the current date and time to be included in output messages.
+# Default is false, and will output the number of milliseconds elapsed since startup.
+org.slf4j.simpleLogger.showDateTime=true
+
+# The date and time format to be used in the output messages.
+# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
+# If the format is not specified or is invalid, the default format is used.
+# The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
+org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z
+
+# Set to true if you want to output the current thread name.
+# Defaults to true.
+org.slf4j.simpleLogger.showThreadName=true
+
+# Set to true if you want the Logger instance name to be included in output messages.
+# Defaults to true.
+#org.slf4j.simpleLogger.showLogName=true
+
+# Set to true if you want the last component of the name to be included in output messages.
+# Defaults to false.
+#org.slf4j.simpleLogger.showShortLogName=false