33import org .slf4j .Logger ;
44import org .slf4j .LoggerFactory ;
55
6- // {{start:logback}}
6+
77public class LogbackExamples {
8+ // {{start:slf4j}}
89 /*
910 * Loggers are thread safe so it is okay to make them static.
1011 * Sometimes you may want to pass instances though, it's up to you.
1112 */
1213 private static final Logger logger = LoggerFactory .getLogger (LogbackExamples .class );
1314 private static final Logger secretLogger = LoggerFactory .getLogger ("com.stubbornjava.secrets.MySecretPasswordClass" );
1415
15- public static void main (String [] args ) {
16-
16+ public static void logLevels () {
1717 logger .trace ("TRACE" );
1818 logger .info ("INFO" );
1919 logger .debug ("DEBUG" );
@@ -26,6 +26,50 @@ public static void main(String[] args) {
2626 secretLogger .warn ("WARN" );
2727 secretLogger .error ("ERROR" );
2828 }
29+ // {{end:slf4j}}
30+
31+ // {{start:slf4jFormat}}
32+ public static void logFormat () {
33+ logger .info ("Hello {}" , "world" );
34+
35+ for (int i = 0 ; i < 5 ; i ++) {
36+ logger .info ("Hello {} i={}" , "world" , i );
37+ }
38+ }
39+ // {{end:slf4jFormat}}
40+
41+ // {{start:slf4jConditionalLogging}}
42+ public static void conditionalLogging () {
43+
44+ if (logger .isInfoEnabled ()) {
45+ Object expensiveCall = null ;
46+ logger .info ("Logger expensive call {}" , expensiveCall );
47+ }
48+
49+ if (secretLogger .isInfoEnabled ()) {
50+ Object expensiveCall = null ;
51+ logger .info ("Secret expensive call {}" , expensiveCall );
52+ }
53+ }
54+ // {{end:slf4jConditionalLogging}}
55+
56+
57+ // {{start:slf4jException}}
58+ public static void logException () {
59+ try {
60+ throw new RuntimeException ("What happened?" );
61+ } catch (Exception ex ) {
62+ logger .warn ("Something bad happened" , ex );
63+ logger .warn ("Something bad happened with id: {}" , 1 , ex );
64+ }
65+ }
66+ // {{end:slf4jException}}
67+
68+ public static void main (String [] args ) {
69+ logLevels ();
70+ logFormat ();
71+ conditionalLogging ();
72+ logException ();
73+ }
2974}
30- // {{end:logback}}
3175
0 commit comments