HI. . .  I had a lot of JUL logp code to convert to SLF4J so I tweaked the
migrator in a few ways:

* Added MultiLineConversionRule to accommodate cases such as:
   log.logp(Level.FINEST, MyClass.class.getName(),
 "myMethod", "Log entry");
* Passed Reader into LineConverter in order to more easily control reading
in of additional lines
* Changed ConversionRule.replace() to append the match.group(1) text to the
replacement line if group(1) exists
* Added additional SingleConversionRules to accommodate additional logp
scenarios

I converted quite a bit of code with minimal cleanup.  Where that was
necessary was pretty unavoidable:

* Code using Level, handlers, custom configuration, etc
* Log entries with commas get a bit mungled, e.g.:
   log.logp(Level.FINEST, MyClass.class.getName(),
"myMethod", "This, e.g., would get mungled");

I did not do any regression testing but it worked in my case.  Attaching the
patch file in case I'm not the only slf4j fan converting logps!

Andy






-- 
*Andy Jewell  *
*Build Engineer
*503.752.6137 | [email protected] <http://twitter.com/bite4size>

Become your household CFO, visit Adaptu.com <https://www.adaptu.com/>
diff -Naur slf4j/slf4j-migrator/src/main/java/org/slf4j/migrator/InplaceFileConverter.java slf4j-upd/main/java/org/slf4j/migrator/InplaceFileConverter.java
--- slf4j/slf4j-migrator/src/main/java/org/slf4j/migrator/InplaceFileConverter.java	2011-08-05 09:02:43.000000000 -0700
+++ slf4j-upd/main/java/org/slf4j/migrator/InplaceFileConverter.java	2011-08-05 10:36:43.000000000 -0700
@@ -45,11 +45,11 @@
     byte[] originalBytes = readIntoByteArray(file);
     byte[] convertedBytes = convertIntoTempByteArray(originalBytes);
     if (lineConverter.atLeastOneMatchOccured()) {
-      //System.out.println("Converting ["+file+"]");
+      // System.out.println("Converting ["+file+"]");
       writeConvertedBytesIntoFile(file, convertedBytes);
       pl.onInplaceConversion(file);
     } else {
-      //System.out.println("Not touching ["+file+"]");
+      // System.out.println("Not touching ["+file+"]");
     }
   }
 
@@ -60,22 +60,22 @@
     fos.close();
   }
 
-  private byte[] convertIntoTempByteArray(byte[] input) throws IOException {
-    ByteArrayInputStream bais = new ByteArrayInputStream(input);
-    Reader reader = new InputStreamReader(bais);
-    BufferedReader breader = new BufferedReader(reader);
-    ByteArrayOutputStream baos = new ByteArrayOutputStream();
-    while (true) {
-      String line = breader.readLine();
-      if (line != null) {
-        String[] replacement = lineConverter.getReplacement(line);
-        writeReplacement(baos, replacement);
-      } else {
-        break;
-      }
-    }
-    return baos.toByteArray();
-  }
+	private byte[] convertIntoTempByteArray(byte[] input) {
+		ByteArrayOutputStream baos = null;
+		try {
+			ByteArrayInputStream bais = new ByteArrayInputStream(input);
+			Reader reader = new InputStreamReader(bais);
+			BufferedReader breader = new BufferedReader(reader);
+			//PushbackLineReader pbreader = new PushbackLineReader(breader,1000);
+			baos = new ByteArrayOutputStream();
+			String[] replacement = lineConverter.getReplacement(breader);
+			writeReplacement(baos, replacement);
+		} catch (IOException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		return baos.toByteArray();
+	}
 
   private  void writeReplacement(OutputStream os, String[] replacement)
       throws IOException {
diff -Naur slf4j/slf4j-migrator/src/main/java/org/slf4j/migrator/line/ConversionRule.java slf4j-upd/main/java/org/slf4j/migrator/line/ConversionRule.java
--- slf4j/slf4j-migrator/src/main/java/org/slf4j/migrator/line/ConversionRule.java	2011-08-05 09:02:43.000000000 -0700
+++ slf4j-upd/main/java/org/slf4j/migrator/line/ConversionRule.java	2011-08-05 10:36:43.000000000 -0700
@@ -48,4 +48,10 @@
    */
   public String getAdditionalLine();
 
+	/**
+	 * If two patterns - first line and second line - required for a match
+	 * @return	true if this is a multiline rule
+	 */
+	public boolean isMultiline();
+
 }
\ No newline at end of file
diff -Naur slf4j/slf4j-migrator/src/main/java/org/slf4j/migrator/line/JULRuleSet.java slf4j-upd/main/java/org/slf4j/migrator/line/JULRuleSet.java
--- slf4j/slf4j-migrator/src/main/java/org/slf4j/migrator/line/JULRuleSet.java	2011-08-05 09:02:43.000000000 -0700
+++ slf4j-upd/main/java/org/slf4j/migrator/line/JULRuleSet.java	2011-08-05 10:36:43.000000000 -0700
@@ -2,6 +2,7 @@
 
 import java.util.ArrayList;
 import java.util.Iterator;
+import java.util.logging.Level;
 import java.util.regex.Pattern;
 
 /**
@@ -23,35 +24,91 @@
         "import org.slf4j.LoggerFactory;");
     
     SingleConversionRule crImport1 = new SingleConversionRule(Pattern
-        .compile("import\\s*+org.apache.log4j.LogManager;"),
-        "import org.slf4j.LoggerFactory;");
-
-    SingleConversionRule crImport2 = new SingleConversionRule(Pattern
-        .compile("import\\s*+java.util.logging.*;"),
-        "import org.slf4j.Logger;",
-        "import org.slf4j.LoggerFactory;");
+        .compile("import\\s*+java.util.logging.Level;"),
+        "");
 
-
-    SingleConversionRule crFactory0 = new SingleConversionRule(Pattern
+   SingleConversionRule crFactory0 = new SingleConversionRule(Pattern
         .compile("Logger.getLogger\\("), "LoggerFactory.getLogger(");
 
-    SingleConversionRule crFactory1 = new SingleConversionRule(Pattern
-        .compile("LogManager.getLogger\\("), "LoggerFactory.getLogger(");
+   SingleConversionRule crFactory1 = new SingleConversionRule(Pattern
+       .compile("LogManager.getLogger\\("), "LoggerFactory.getLogger(");
 
     SingleConversionRule crWarning = new SingleConversionRule(Pattern
             .compile("\\.warning\\("), ".warn(");
     SingleConversionRule crSevere = new SingleConversionRule(Pattern
             .compile("\\.severe\\("), ".error(");
-  
+    SingleConversionRule crFine = new SingleConversionRule(Pattern
+    		.compile("\\.fine\\("), ".debug(");
+    SingleConversionRule crFiner = new SingleConversionRule(Pattern
+    		.compile("\\.finer\\("), ".trace(");
+    SingleConversionRule crFinest = new SingleConversionRule(Pattern
+    		.compile("\\.finest\\("), ".trace(");
+    
+    // additional single conversion rules for logp logging - since
+    // they also gobble up the newline, add it as an additional line
+    SingleConversionRule crml_logpFinest =  new SingleConversionRule(Pattern
+            .compile("\\.logp\\(Level.FINEST,.*\\, ?\"(.*;)\\s*")
+            ,".trace(\""
+            ,System.getProperty("line.separator"));
+    SingleConversionRule crml_logpFiner =  new SingleConversionRule(Pattern
+    		.compile("\\.logp\\(Level.FINER,.*\\, ?\"(.*;)\\s*")
+    		,".trace(\""
+    		,System.getProperty("line.separator"));
+    SingleConversionRule crml_logpFine =  new SingleConversionRule(Pattern
+    		.compile("\\.logp\\(Level.FINE,.*\\, ?\"(.*;)\\s*")
+    		,".debug(\""
+    		,System.getProperty("line.separator"));
+    SingleConversionRule crml_isloggable =  new SingleConversionRule(Pattern
+    		.compile("(\\.isLoggable\\(Level.FINE[RS]T?\\))")
+    		,".isDebugEnabled()");
+
+    MultiLineConversionRule crml_crTrace1 = new MultiLineConversionRule(Pattern.compile("logp\\(Level.FINEST.*,(.*)")
+    		,Pattern.compile("^.*;\\s*$")
+    		,Pattern.compile("(logp\\(Level.FINEST.*,\\s*(.*))")
+    		,"trace(");
+    MultiLineConversionRule crml_crTrace2 = new MultiLineConversionRule(Pattern.compile("logp\\(Level.FINER.*,(.*)")
+    		,Pattern.compile("^.*;\\s*$")
+    		,Pattern.compile("(logp\\(Level.FINER.*,\\s*(.*))")
+    		,"trace(");
+    MultiLineConversionRule crml_crDebug = new MultiLineConversionRule(Pattern.compile("logp\\(Level.FINE,(.*)")
+    		,Pattern.compile("^.*;\\s*$")
+    		,Pattern.compile("(logp\\(Level.FINE,.*,\\s*(.*))")
+    		,"debug(");
+    MultiLineConversionRule crml_crInfo = new MultiLineConversionRule(Pattern.compile("logp\\(Level.INFO.*,(.*)")
+    		,Pattern.compile("^.*;\\s*$")
+    		,Pattern.compile("(logp\\(Level.INFO.*,\\s*(.*))")
+    		,"info(");
+    MultiLineConversionRule crml_crSevere = new MultiLineConversionRule(Pattern.compile("logp\\(Level.WARNING.*,(.*)")
+    		,Pattern.compile("^.*;\\s*$")
+    		,Pattern.compile("(logp\\(Level.WARNING.*,\\s*(.*))")
+    		,"warn(");
+    MultiLineConversionRule crml_crWarn = new MultiLineConversionRule(Pattern.compile("logp\\(Level.SEVERE.*,(.*)")
+    		,Pattern.compile("^.*;\\s*$")
+    		,Pattern.compile("(logp\\(Level.SEVERE.*,\\s*(.*))")
+    		,"error(");
     
     conversionRuleList = new ArrayList<ConversionRule>();
     conversionRuleList.add(crImport0);
     conversionRuleList.add(crImport1);
-    conversionRuleList.add(crImport2);
+    // conversionRuleList.add(crImport2);
     conversionRuleList.add(crFactory0);
     conversionRuleList.add(crFactory1);
     conversionRuleList.add(crWarning);
     conversionRuleList.add(crSevere);
+    conversionRuleList.add(crFine);
+    conversionRuleList.add(crFiner);
+    conversionRuleList.add(crFinest);
+    conversionRuleList.add(crml_logpFine);
+    conversionRuleList.add(crml_logpFiner);
+    conversionRuleList.add(crml_logpFinest);
+    // multiline rules should be last so that single line logp messages are converted first
+    conversionRuleList.add(crml_crTrace1);
+    conversionRuleList.add(crml_crTrace2);
+    conversionRuleList.add(crml_crDebug);
+    conversionRuleList.add(crml_crInfo);
+    conversionRuleList.add(crml_crSevere);
+    conversionRuleList.add(crml_crWarn); 
+    conversionRuleList.add(crml_isloggable); 
   }
 
   public Iterator<ConversionRule> iterator() {
diff -Naur slf4j/slf4j-migrator/src/main/java/org/slf4j/migrator/line/LineConverter.java slf4j-upd/main/java/org/slf4j/migrator/line/LineConverter.java
--- slf4j/slf4j-migrator/src/main/java/org/slf4j/migrator/line/LineConverter.java	2011-08-05 09:02:43.000000000 -0700
+++ slf4j-upd/main/java/org/slf4j/migrator/line/LineConverter.java	2011-08-05 10:36:43.000000000 -0700
@@ -1,7 +1,10 @@
 package org.slf4j.migrator.line;
 
-import java.util.Arrays;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.util.ArrayList;
 import java.util.Iterator;
+import java.util.List;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -14,7 +17,6 @@
   public LineConverter(RuleSet ruleSet) {
     this.ruleSet = ruleSet;
   }
-
   /**
    * Check if the specified text is matching some conversions rules. 
    * If a rule matches, ask for line replacement.
@@ -22,46 +24,83 @@
    * <p>In case no rule can be applied, then the input text is
    * returned without change.
    * 
-   * @param text
-   * @return String
+   * @param pbreader filereader
+   * @return String[] to write to output (if modified)
    */
-  public String[] getReplacement(String text) {
-    ConversionRule conversionRule;
-    Pattern pattern;
-    Matcher matcher;
-    Iterator<ConversionRule> conversionRuleIterator = ruleSet.iterator();
-    String additionalLine = null;
-    while (conversionRuleIterator.hasNext()) {
-      conversionRule = conversionRuleIterator.next();
-      pattern = conversionRule.getPattern();
-      matcher = pattern.matcher(text);
-      if (matcher.find()) {
-        // System.out.println("matching " + text);
-        atLeastOneMatchOccured = true;
-        String replacementText = conversionRule.replace(matcher);
-        text = matcher.replaceAll(replacementText);
-        if(conversionRule.getAdditionalLine() != null) {
-          additionalLine = conversionRule.getAdditionalLine();
-        }
-      }
-    }
-    
-    if(additionalLine == null) {
-      return new String[] {text};
-    } else {
-      return new String[] {text, additionalLine};
-    }
-  }
+	public String[] getReplacement(BufferedReader pbreader) {
+		ConversionRule conversionRule;
+		Pattern pattern;
+		Matcher matcher;
+		String additionalLine = null;
+		List<String> rewrite = null;
+		try {
+			String text = pbreader.readLine();
+			rewrite = new ArrayList<String>();
+			while (text != null) {
+				Iterator<ConversionRule> conversionRuleIterator = ruleSet.iterator();
+				while (conversionRuleIterator.hasNext()) {
+					conversionRule = conversionRuleIterator.next();
+					pattern = conversionRule.getPattern();
+					matcher = pattern.matcher(text);
+					if (matcher.find()) {
+						atLeastOneMatchOccured = true;
+						// System.out.println("matching " + text);
+						String replacementText = "";
+						// multiline rule match
+						if (conversionRule.isMultiline()) {
+							// get second line
+							// keep reading lines until we match the second pattern
+							String nextline = pbreader.readLine();
+							StringBuffer fulltext = new StringBuffer(text);
+							// ** Get the second pattern **
+							Pattern secondline = conversionRule.getPattern();
+							while(nextline!=null){
+								Matcher secondm = secondline.matcher(nextline);
+								if (secondm.find()) {
+									fulltext.append(nextline);
+									// get the final replacement pattern (pattern 3)
+									Pattern p = conversionRule.getPattern();
+									String appended = fulltext.toString();
+									matcher = p.matcher(appended);
+									atLeastOneMatchOccured = true;
+									break;
+								} else {
+									fulltext.append(nextline);
+								}
+								nextline = pbreader.readLine();
+							}
+						}
+						if (conversionRule.getAdditionalLine() != null) {
+							additionalLine = conversionRule.getAdditionalLine();
+						}
+						// rule was matched (either single or multiline)
+						replacementText = conversionRule.replace(matcher);
+						text = matcher.replaceAll(replacementText);
+					} // end rule matched
+					if (conversionRule.isMultiline())
+						((MultiLineConversionRule) conversionRule).resetPatternList();
+
+				}
+				if (additionalLine == null) {
+					rewrite.add(text);
+				} else {
+					rewrite.add(text);
+					rewrite.add(additionalLine);
+					//return new String[] { text, additionalLine };
+				}
+				text = pbreader.readLine();
+				additionalLine = null;
+			}
+		} catch (IOException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		return rewrite.toArray(new String[]{});
+	}
 
-  public String getOneLineReplacement(String text) {
-    String[] r = getReplacement(text);
-    if(r.length != 1) {
-      throw new IllegalStateException("Expecting a single string but got "+Arrays.toString(r));
-    } else {
-      return r[0];
-    }
-  }
   public boolean atLeastOneMatchOccured() {
     return atLeastOneMatchOccured;
   }
+
+
 }
diff -Naur slf4j/slf4j-migrator/src/main/java/org/slf4j/migrator/line/MultiGroupConversionRule.java slf4j-upd/main/java/org/slf4j/migrator/line/MultiGroupConversionRule.java
--- slf4j/slf4j-migrator/src/main/java/org/slf4j/migrator/line/MultiGroupConversionRule.java	2011-08-05 09:02:43.000000000 -0700
+++ slf4j-upd/main/java/org/slf4j/migrator/line/MultiGroupConversionRule.java	2011-08-05 10:36:43.000000000 -0700
@@ -92,4 +92,10 @@
   public String getAdditionalLine() {
     return null;
   }
+
+	@Override
+	public boolean isMultiline() {
+		// TODO Auto-generated method stub
+		return false;
+	}
 }
diff -Naur slf4j/slf4j-migrator/src/main/java/org/slf4j/migrator/line/MultiLineConversionRule.java slf4j-upd/main/java/org/slf4j/migrator/line/MultiLineConversionRule.java
--- slf4j/slf4j-migrator/src/main/java/org/slf4j/migrator/line/MultiLineConversionRule.java	1969-12-31 16:00:00.000000000 -0800
+++ slf4j-upd/main/java/org/slf4j/migrator/line/MultiLineConversionRule.java	2011-08-05 10:36:43.000000000 -0700
@@ -0,0 +1,70 @@
+package org.slf4j.migrator.line;
+
+import java.util.EnumMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class MultiLineConversionRule implements ConversionRule {
+	enum PatternCycle {First,Second,Third};
+	Map<PatternCycle,Pattern> patternmap = new EnumMap<PatternCycle,Pattern>(PatternCycle.class);
+	int patternnumber = 0;
+	
+	// we expect two calls to replace, hold the full text from both
+	String[] linesToMatch = new String[2];
+	
+	String replacementText = "";
+	public MultiLineConversionRule(Pattern firstlinepattern
+			,Pattern secondlinepattern
+			,Pattern combinedlinepattern
+			,String replacementText) {
+		patternmap.put(PatternCycle.First, firstlinepattern);
+		patternmap.put(PatternCycle.Second, secondlinepattern);
+		patternmap.put(PatternCycle.Third, combinedlinepattern);
+		this.replacementText = replacementText;
+	}
+	
+	public void resetPatternList() {
+		patternnumber = 0;
+	}
+	
+	@Override
+	// get the patterns in succession
+	public Pattern getPattern() {
+		Pattern returnpattern;
+		PatternCycle pc = PatternCycle.values()[patternnumber];
+		returnpattern = patternmap.get(pc);
+		
+		if(patternnumber<2){
+			patternnumber++;
+		}
+		return returnpattern;
+	}
+
+	@Override
+	public String replace(Matcher matcher) {
+		String replacewith = "WHAT??  You shouldn't be using me yet, you haven't checked the second line!!";
+		
+		// typical two-line logp
+		//log.logp(Level.FINEST, Deployment.class.getName(), "Deployment",
+		if(patternnumber==2){
+			if(matcher.find()){
+				replacewith = replacementText+matcher.group(2);
+			} 
+		}
+		return replacewith;
+	}
+
+	@Override
+	public String getAdditionalLine() {
+		// TODO Auto-generated method stub
+		return null;
+	}
+
+	@Override
+	public boolean isMultiline() {
+		// TODO Auto-generated method stub
+		return true;
+	}
+
+}
diff -Naur slf4j/slf4j-migrator/src/main/java/org/slf4j/migrator/line/SingleConversionRule.java slf4j-upd/main/java/org/slf4j/migrator/line/SingleConversionRule.java
--- slf4j/slf4j-migrator/src/main/java/org/slf4j/migrator/line/SingleConversionRule.java	2011-08-05 09:02:43.000000000 -0700
+++ slf4j-upd/main/java/org/slf4j/migrator/line/SingleConversionRule.java	2011-08-05 10:36:43.000000000 -0700
@@ -63,12 +63,31 @@
   /* (non-Javadoc)
    * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher)
    */
-  public String replace(Matcher matcher) {
-    return replacementText;
-  }
+	public String replace(Matcher matcher) {
+		String grouptext = null;
+		String replace = replacementText;
+		try {
+			grouptext = matcher.group(1);
+			replace = replacementText + grouptext;
+		} catch (IndexOutOfBoundsException e) {
+			// there was apparently
+		}
+		return replace;
+	}
 
   public String getAdditionalLine() {
     return additionalLine;
   }
 
+	/*
+	 * (non-Javadoc)
+	 * 
+	 * @see org.slf4j.migrator.line.ConversionRule#isMultiline()
+	 */
+	@Override
+	public boolean isMultiline() {
+		// TODO Auto-generated method stub
+		return false;
+	}
+
 }
diff -Naur slf4j/slf4j-migrator/src/main/resources/META-INF/MANIFEST.MF slf4j-upd/main/resources/META-INF/MANIFEST.MF
--- slf4j/slf4j-migrator/src/main/resources/META-INF/MANIFEST.MF	2011-08-05 09:02:43.000000000 -0700
+++ slf4j-upd/main/resources/META-INF/MANIFEST.MF	1969-12-31 16:00:00.000000000 -0800
@@ -1 +0,0 @@
-Main-Class: org.slf4j.migrator.Main
\ No newline at end of file
_______________________________________________
slf4j-dev mailing list
[email protected]
http://qos.ch/mailman/listinfo/slf4j-dev

Reply via email to