Wednesday, December 22, 2021

Refactor log4j project to slf4j

HOWTO 

 

Create simple Java project using Maven archetype

$     mvn org.apache.maven.plugins:maven-archetype-plugin:2.4:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4

Define value for property 'groupId': : dave
Define value for property 'artifactId': : simple
Define value for property 'version':  1.0-SNAPSHOT: : 
Define value for property 'package':  dave: : 
Confirm properties configuration:
groupId: dave
artifactId: simple
version: 1.0-SNAPSHOT
package: dave
 Y: : Y 
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Archetype: maven-archetype-quickstart:1.4
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: dave
[INFO] Parameter: artifactId, Value: simple
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: package, Value: dave
[INFO] Parameter: packageInPathFormat, Value: dave
[INFO] Parameter: package, Value: dave
[INFO] Parameter: groupId, Value: dave
[INFO] Parameter: artifactId, Value: simple
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Archetype in dir: /git/simple/simple
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  36.314 s
[INFO] Finished at: 2021-12-22T22:03:21+01:00
[INFO] ------------------------------------------------------------------------
[dave@dave simple]$ find
.
./simple
./simple/pom.xml
./simple/src
./simple/src/main
./simple/src/main/java
./simple/src/main/java/dave
./simple/src/main/java/dave/App.java
./simple/src/test
./simple/src/test/java
./simple/src/test/java/dave
./simple/src/test/java/dave/AppTest.java
[dave@dave simple]$ 

Add log4j Maven dependency
  <!-- https://mvnrepository.com/artifact/log4j/log4j -->
   <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
   </dependency>

Add log4j 1.2 call
package dave;

// Import log4j classes.
import org.apache.log4j.*;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args )
    {

   // get a logger instance named "com.foo"
   Logger  logger = Logger.getLogger("com.foo");

   Logger barlogger = Logger.getLogger("com.foo.Bar");

   // This request is enabled, because WARN >= INFO.
   logger.warn("Low fuel level.");

   // This request is disabled, because DEBUG < INFO.
   logger.debug("Starting search for nearest gas station.");

   // The logger instance barlogger, named "com.foo.Bar",
   // will inherit its level from the logger named
   // "com.foo" Thus, the following request is enabled
   // because INFO >= INFO.
   barlogger.info("Located nearest gas station.");

   // This request is disabled, because DEBUG < INFO.
   barlogger.debug("Exiting gas station search");
    }

}

Add rewrite plugin
      <plugin>
        <groupId>org.openrewrite.maven</groupId>
        <artifactId>rewrite-maven-plugin</artifactId>
        <version>4.14.1</version>
        <configuration>
          <activeRecipes>
            <recipe>org.openrewrite.java.logging.slf4j.Log4jToSlf4j</recipe>
          </activeRecipes>
        </configuration>
        <dependencies>
          <dependency>
            <groupId>org.openrewrite.recipe</groupId>
            <artifactId>rewrite-logging-frameworks</artifactId>
            <version>0.9.0</version>
          </dependency>
        </dependencies>
      </plugin>

Discover
[INFO] Available Recipes:
[INFO]                 org.openrewrite.DeleteSourceFiles
[INFO]                 org.openrewrite.FindSourceFiles
[INFO]                 org.openrewrite.RenameFile
[INFO]                 org.openrewrite.hcl.format.AutoFormat
[INFO]                 org.openrewrite.hcl.format.NormalizeFormat
[INFO]                 org.openrewrite.hcl.format.RemoveTrailingWhitespace
[INFO]                 org.openrewrite.hcl.format.Spaces
[INFO]                 org.openrewrite.hcl.format.TabsAndIndents
[INFO]                 org.openrewrite.java.AddLicenseHeader
[INFO]                 org.openrewrite.java.ChangeMethodAccessLevel
[INFO]                 org.openrewrite.java.ChangeMethodName
[INFO]                 org.openrewrite.java.ChangeMethodTargetToStatic
[INFO]                 org.openrewrite.java.ChangeMethodTargetToVariable
[INFO]                 org.openrewrite.java.ChangePackage
[INFO]                 org.openrewrite.java.ChangeType
[INFO]                 org.openrewrite.java.DeleteMethodArgument
[INFO]                 org.openrewrite.java.GenerateGetter
[INFO]                 org.openrewrite.java.NoStaticImport
[INFO]                 org.openrewrite.java.OrderImports
[INFO]                 org.openrewrite.java.RemoveAnnotation
[INFO]                 org.openrewrite.java.RemoveUnusedImports
[INFO]                 org.openrewrite.java.ReorderMethodArguments
[INFO]                 org.openrewrite.java.SimplifyMethodChain
[INFO]                 org.openrewrite.java.UseStaticImport
[INFO]                 org.openrewrite.java.cleanup.AtomicPrimitiveEqualsUsesGet
[INFO]                 org.openrewrite.java.cleanup.BigDecimalRoundingConstantsToEnums
[INFO]                 org.openrewrite.java.cleanup.BooleanChecksNotInverted
[INFO]                 org.openrewrite.java.cleanup.CaseInsensitiveComparisonsDoNotChangeCase
[INFO]                 org.openrewrite.java.cleanup.CatchClauseOnlyRethrows
[INFO]                 org.openrewrite.java.cleanup.ControlFlowIndentation
[INFO]                 org.openrewrite.java.cleanup.CovariantEquals
[INFO]                 org.openrewrite.java.cleanup.DefaultComesLast
[INFO]                 org.openrewrite.java.cleanup.EmptyBlock
[INFO]                 org.openrewrite.java.cleanup.EqualsAvoidsNull
[INFO]                 org.openrewrite.java.cleanup.ExplicitInitialization
[INFO]                 org.openrewrite.java.cleanup.ExplicitLambdaArgumentTypes
[INFO]                 org.openrewrite.java.cleanup.ExternalizableHasNoArgsConstructor
[INFO]                 org.openrewrite.java.cleanup.FallThrough
[INFO]                 org.openrewrite.java.cleanup.FinalClass
[INFO]                 org.openrewrite.java.cleanup.FinalizeLocalVariables
[INFO]                 org.openrewrite.java.cleanup.FixSerializableFields
[INFO]                 org.openrewrite.java.cleanup.ForLoopControlVariablePostfixOperators
[INFO]                 org.openrewrite.java.cleanup.ForLoopIncrementInUpdate
[INFO]                 org.openrewrite.java.cleanup.HiddenField
[INFO]                 org.openrewrite.java.cleanup.HideUtilityClassConstructor
[INFO]                 org.openrewrite.java.cleanup.IndexOfChecksShouldUseAStartPosition
[INFO]                 org.openrewrite.java.cleanup.IndexOfReplaceableByContains
[INFO]                 org.openrewrite.java.cleanup.IndexOfShouldNotCompareGreaterThanZero
[INFO]                 org.openrewrite.java.cleanup.IsEmptyCallOnCollections
[INFO]                 org.openrewrite.java.cleanup.LambdaBlockToExpression
[INFO]                 org.openrewrite.java.cleanup.MethodNameCasing
[INFO]                 org.openrewrite.java.cleanup.MethodParamPad
[INFO]                 org.openrewrite.java.cleanup.MinimumSwitchCases
[INFO]                 org.openrewrite.java.cleanup.MissingOverrideAnnotation
[INFO]                 org.openrewrite.java.cleanup.ModifierOrder
[INFO]                 org.openrewrite.java.cleanup.MultipleVariableDeclarations
[INFO]                 org.openrewrite.java.cleanup.NeedBraces
[INFO]                 org.openrewrite.java.cleanup.NestedEnumsAreNotStatic
[INFO]                 org.openrewrite.java.cleanup.NewStringBuilderBufferWithCharArgument
[INFO]                 org.openrewrite.java.cleanup.NoDoubleBraceInitialization
[INFO]                 org.openrewrite.java.cleanup.NoEmptyCollectionWithRawType
[INFO]                 org.openrewrite.java.cleanup.NoEqualityInForCondition
[INFO]                 org.openrewrite.java.cleanup.NoFinalizer
[INFO]                 org.openrewrite.java.cleanup.NoRedundantJumpStatements
[INFO]                 org.openrewrite.java.cleanup.NoToStringOnStringType
[INFO]                 org.openrewrite.java.cleanup.NoValueOfOnStringType
[INFO]                 org.openrewrite.java.cleanup.NoWhitespaceAfter
[INFO]                 org.openrewrite.java.cleanup.NoWhitespaceBefore
[INFO]                 org.openrewrite.java.cleanup.OperatorWrap
[INFO]                 org.openrewrite.java.cleanup.PadEmptyForLoopComponents
[INFO]                 org.openrewrite.java.cleanup.PrimitiveWrapperClassConstructorToValueOf
[INFO]                 org.openrewrite.java.cleanup.RedundantFileCreation
[INFO]                 org.openrewrite.java.cleanup.RemoveExtraSemicolons
[INFO]                 org.openrewrite.java.cleanup.RemoveUnusedLocalVariables
[INFO]                 org.openrewrite.java.cleanup.RemoveUnusedPrivateMethods
[INFO]                 org.openrewrite.java.cleanup.RenameLocalVariablesToCamelCase
[INFO]                 org.openrewrite.java.cleanup.RenameMethodsNamedHashcodeEqualOrTostring
[INFO]                 org.openrewrite.java.cleanup.SimplifyBooleanExpression
[INFO]                 org.openrewrite.java.cleanup.SimplifyBooleanReturn
[INFO]                 org.openrewrite.java.cleanup.StaticMethodNotFinal
[INFO]                 org.openrewrite.java.cleanup.StringLiteralEquality
[INFO]                 org.openrewrite.java.cleanup.TypecastParenPad
[INFO]                 org.openrewrite.java.cleanup.UnnecessaryCloseInTryWithResources
[INFO]                 org.openrewrite.java.cleanup.UnnecessaryExplicitTypeArguments
[INFO]                 org.openrewrite.java.cleanup.UnnecessaryParentheses
[INFO]                 org.openrewrite.java.cleanup.UnnecessaryPrimitiveAnnotations
[INFO]                 org.openrewrite.java.cleanup.UnnecessaryThrows
[INFO]                 org.openrewrite.java.cleanup.UseCollectionInterfaces
[INFO]                 org.openrewrite.java.cleanup.UseDiamondOperator
[INFO]                 org.openrewrite.java.cleanup.UseFilesCreateTempDirectory
[INFO]                 org.openrewrite.java.cleanup.UseJavaStyleArrayDeclarations
[INFO]                 org.openrewrite.java.cleanup.UseLambdaForFunctionalInterface
[INFO]                 org.openrewrite.java.cleanup.WhileInsteadOfFor
[INFO]                 org.openrewrite.java.cleanup.WriteOctalValuesAsDecimal
[INFO]                 org.openrewrite.java.format.AutoFormat
[INFO]                 org.openrewrite.java.format.BlankLines
[INFO]                 org.openrewrite.java.format.EmptyNewlineAtEndOfFile
[INFO]                 org.openrewrite.java.format.NormalizeFormat
[INFO]                 org.openrewrite.java.format.NormalizeLineBreaks
[INFO]                 org.openrewrite.java.format.NormalizeTabsOrSpaces
[INFO]                 org.openrewrite.java.format.RemoveTrailingWhitespace
[INFO]                 org.openrewrite.java.format.SingleLineComments
[INFO]                 org.openrewrite.java.format.Spaces
[INFO]                 org.openrewrite.java.format.TabsAndIndents
[INFO]                 org.openrewrite.java.format.WrappingAndBraces
[INFO]                 org.openrewrite.java.logging.PrintStackTraceToLogError
[INFO]                 org.openrewrite.java.logging.log4j.PrependRandomName
[INFO]                 org.openrewrite.java.logging.logback.Log4jAppenderToLogback
[INFO]                 org.openrewrite.java.logging.logback.Log4jLayoutToLogback
[INFO]                 org.openrewrite.java.logging.slf4j.Log4jToSlf4j
[INFO]                 org.openrewrite.java.logging.slf4j.ParameterizedLogging
[INFO]                 org.openrewrite.java.search.FindAnnotations
[INFO]                 org.openrewrite.java.search.FindDeprecatedClasses
[INFO]                 org.openrewrite.java.search.FindDeprecatedFields
[INFO]                 org.openrewrite.java.search.FindDeprecatedMethods
[INFO]                 org.openrewrite.java.search.FindDeprecatedUses
[INFO]                 org.openrewrite.java.search.FindEmptyClasses
[INFO]                 org.openrewrite.java.search.FindFields
[INFO]                 org.openrewrite.java.search.FindFieldsOfType
[INFO]                 org.openrewrite.java.search.FindMethods
[INFO]                 org.openrewrite.java.search.FindMissingTypes
[INFO]                 org.openrewrite.java.search.FindText
[INFO]                 org.openrewrite.java.search.FindTypes
[INFO]                 org.openrewrite.java.search.ResultOfMethodCallIgnored
[INFO]                 org.openrewrite.json.ChangeKey
[INFO]                 org.openrewrite.json.ChangeValue
[INFO]                 org.openrewrite.json.DeleteKey
[INFO]                 org.openrewrite.json.search.FindKey
[INFO]                 org.openrewrite.maven.AddDependency
[INFO]                 org.openrewrite.maven.AddPlugin
[INFO]                 org.openrewrite.maven.ChangeDependencyGroupIdAndArtifactId
[INFO]                 org.openrewrite.maven.ChangeDependencyScope
[INFO]                 org.openrewrite.maven.ChangePropertyValue
[INFO]                 org.openrewrite.maven.ExcludeDependency
[INFO]                 org.openrewrite.maven.ManageDependencies
[INFO]                 org.openrewrite.maven.OrderPomElements
[INFO]                 org.openrewrite.maven.RemoveDependency
[INFO]                 org.openrewrite.maven.RemoveExclusion
[INFO]                 org.openrewrite.maven.RemovePlugin
[INFO]                 org.openrewrite.maven.RemoveProperty
[INFO]                 org.openrewrite.maven.RemoveRedundantDependencyVersions
[INFO]                 org.openrewrite.maven.UpgradeDependencyVersion
[INFO]                 org.openrewrite.maven.UpgradeParentVersion
[INFO]                 org.openrewrite.maven.UpgradePluginVersion
[INFO]                 org.openrewrite.maven.search.DependencyInsight
[INFO]                 org.openrewrite.maven.search.FindDependency
[INFO]                 org.openrewrite.maven.search.FindPlugin
[INFO]                 org.openrewrite.maven.search.FindProperties
[INFO]                 org.openrewrite.properties.ChangePropertyKey
[INFO]                 org.openrewrite.properties.ChangePropertyValue
[INFO]                 org.openrewrite.properties.DeleteProperty
[INFO]                 org.openrewrite.properties.search.FindProperties
[INFO]                 org.openrewrite.text.ChangeText
[INFO]                 org.openrewrite.text.CreateTextFile
[INFO]                 org.openrewrite.xml.AutoFormat
[INFO]                 org.openrewrite.xml.search.FindTags
[INFO]                 org.openrewrite.yaml.ChangeKey
[INFO]                 org.openrewrite.yaml.ChangePropertyKey
[INFO]                 org.openrewrite.yaml.ChangeValue
[INFO]                 org.openrewrite.yaml.CoalesceProperties
[INFO]                 org.openrewrite.yaml.CopyValue
[INFO]                 org.openrewrite.yaml.DeleteKey
[INFO]                 org.openrewrite.yaml.DeleteProperty
[INFO]                 org.openrewrite.yaml.MergeYaml
[INFO]                 org.openrewrite.yaml.cleanup.RemoveUnused
[INFO]                 org.openrewrite.yaml.format.Indents
[INFO]                 org.openrewrite.yaml.search.FindKey
[INFO]                 org.openrewrite.yaml.search.FindProperty
[INFO]                 org.openrewrite.java.logging.logback.Log4jToLogback
[INFO]                 org.openrewrite.java.cleanup.Cleanup
[INFO]                 org.openrewrite.java.cleanup.CommonStaticAnalysis
[INFO]                 org.openrewrite.java.AddApache2LicenseHeader
[INFO]                 org.openrewrite.java.search.FindSecrets
[INFO] 
[INFO] Available Styles:
[INFO]     com.netflix.genie.Style
[INFO]     org.openrewrite.java.SpringFormat
[INFO]     org.openrewrite.java.GoogleJavaFormat
[INFO]     com.netflix.eureka.Style
[INFO] 
[INFO] Active Styles:
[INFO] 
[INFO] Active Recipes:
[INFO]                 org.openrewrite.java.logging.slf4j.Log4jToSlf4j
[INFO] 
[INFO] Found 173 available recipes and 4 available styles.
[INFO] Configured with 1 active recipes and 1 active styles.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

Run rewrite
[dave@dave simple]$ mvn rewrite:run
[INFO] Scanning for projects...
[INFO] 
[INFO] ----------------------------< dave:simple >-----------------------------
[INFO] Building simple 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] >>> rewrite-maven-plugin:4.14.1:run (default-cli) > process-test-classes @ simple >>>
[INFO] 
[INFO] --- maven-resources-plugin:3.0.2:resources (default-resources) @ simple ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /git/simple/simple/src/main/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ simple ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /git/simple/simple/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:3.0.2:testResources (default-testResources) @ simple ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /git/simple/simple/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ simple ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] <<< rewrite-maven-plugin:4.14.1:run (default-cli) < process-test-classes @ simple <<<
[INFO] 
[INFO] 
[INFO] --- rewrite-maven-plugin:4.14.1:run (default-cli) @ simple ---
[INFO] Using active recipe(s) [org.openrewrite.java.logging.slf4j.Log4jToSlf4j]
[INFO] Using active styles(s) []
[INFO] Validating active recipes...
[INFO] Parsing Java main files...
[INFO] Parsing Java test files...
[INFO] Running recipe(s)...
[WARNING] Changes have been made to src/main/java/dave/App.java by:
[WARNING]     org.openrewrite.java.logging.slf4j.Log4jToSlf4j
[WARNING] Please review and commit the results.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS

Refactored code - log4j replaced with slf4j
 git diff src/main/java/dave/App.java
diff --git a/src/main/java/dave/App.java b/src/main/java/dave/App.java
index 179d8ff..39a78c9 100644
--- a/src/main/java/dave/App.java
+++ b/src/main/java/dave/App.java
@@ -1,7 +1,9 @@
 package dave;
 
 // Import log4j classes.
-import org.apache.log4j.*;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Hello world!
@@ -13,14 +15,14 @@ public class App
     {
 
    // get a logger instance named "com.foo"
-   Logger  logger = Logger.getLogger("com.foo");
+   Logger  logger = LoggerFactory.getLogger("com.foo");
 

-   Logger barlogger = Logger.getLogger("com.foo.Bar");
+   Logger barlogger = LoggerFactory.getLogger("com.foo.Bar");
 
    // This request is enabled, because WARN >= INFO.
    logger.warn("Low fuel level.");

package dave;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args )
    {

   // get a logger instance named "com.foo"
   Logger  logger = LoggerFactory.getLogger("com.foo");

   Logger barlogger = LoggerFactory.getLogger("com.foo.Bar");

   // This request is enabled, because WARN >= INFO.
   logger.warn("Low fuel level.");

   // This request is disabled, because DEBUG < INFO.
   logger.debug("Starting search for nearest gas station.");

   // The logger instance barlogger, named "com.foo.Bar",
   // will inherit its level from the logger named
   // "com.foo" Thus, the following request is enabled
   // because INFO >= INFO.
   barlogger.info("Located nearest gas station.");

   // This request is disabled, because DEBUG < INFO.
   barlogger.debug("Exiting gas station search");
    }

}

No comments:

Post a Comment