Created
January 1, 2017 15:41
-
-
Save dhilst/955a8cc4973999d4d7c817e54e9eb0cd to your computer and use it in GitHub Desktop.
logger with class and method name using SLF4J
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Copyright 2017 Daniel Hilst Selli <[email protected] | |
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. | |
*/ | |
package your.pack.age.here; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
/** | |
* Utility class that return a logger with current class and method name. | |
* | |
* I personally import this as static and use it at every needed method: | |
* <pre> | |
* package some.pack.age; | |
* import static your.pack.age.here.MethodLogger.getLogger; | |
* | |
* class SomeClass { | |
* public void someMethod() { getLogger().info("SOMETHING"); } | |
* } | |
*</pre> | |
* The above example will render something like: | |
* 2017-01-01 13:28:33.029 INFO 9129 --- [main] some.pack.age.SomeClass::someMethod : SOMETHING | |
* | |
* Fell free copy paste at your own risk :P | |
* Enjoy! :) | |
*/ | |
public class MethodLogger { | |
private final static String getClassName(int depth) { | |
return Thread.currentThread().getStackTrace()[depth].getClassName(); | |
} | |
private final static String getMethodName(int depth) { | |
return Thread.currentThread().getStackTrace()[depth].getMethodName(); | |
} | |
public final static Logger getLogger() { | |
return LoggerFactory.getLogger(getClassName(3) + "::" + getMethodName(3)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment