Skip to content

Instantly share code, notes, and snippets.

@gary-liguoliang
Last active November 3, 2018 10:32
Show Gist options
  • Save gary-liguoliang/70284ae11351cabed0132ecf37673c1a to your computer and use it in GitHub Desktop.
Save gary-liguoliang/70284ae11351cabed0132ecf37673c1a to your computer and use it in GitHub Desktop.
Convert all java system.out.print to SLF4J
"""
Copyright 2015 Guoliang Li
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
def convert_sout_to_slf4j(java_src_file):
with open(java_src_file) as f:
lines = f.readlines()
import_missing = True
last_import_index = 1
for i, l in enumerate(lines):
if import_missing and l.startswith("import "):
last_import_index = i
if import_missing and "class " in l:
import_missing = False
lines.insert(last_import_index + 1, "import org.slf4j.Logger;\n")
lines.insert(last_import_index + 2, "import org.slf4j.LoggerFactory;\n")
lines.insert(i + 3, " Logger logger = LoggerFactory.getLogger(getClass());")
if "System.out.println(" in l:
ll = l.replace("System.out.println(", "log.info(")
del lines[i]
lines.insert(i, ll)
for l in lines:
print l.strip('\n')
java_src_root = "/projects/java-playground/db/src/main/java/"
for root, dirs, files in os.walk(java_src_root):
for f in files:
if f.endswith(".java"):
java_src_file = os.path.join(root, f)
convert_sout_to_slf4j(java_src_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment