3
3
import org .slf4j .Logger ;
4
4
import org .slf4j .LoggerFactory ;
5
5
6
- // {{start:logback}}
6
+
7
7
public class LogbackExamples {
8
+ // {{start:slf4j}}
8
9
/*
9
10
* Loggers are thread safe so it is okay to make them static.
10
11
* Sometimes you may want to pass instances though, it's up to you.
11
12
*/
12
13
private static final Logger logger = LoggerFactory .getLogger (LogbackExamples .class );
13
14
private static final Logger secretLogger = LoggerFactory .getLogger ("com.stubbornjava.secrets.MySecretPasswordClass" );
14
15
15
- public static void main (String [] args ) {
16
-
16
+ public static void logLevels () {
17
17
logger .trace ("TRACE" );
18
18
logger .info ("INFO" );
19
19
logger .debug ("DEBUG" );
@@ -26,6 +26,50 @@ public static void main(String[] args) {
26
26
secretLogger .warn ("WARN" );
27
27
secretLogger .error ("ERROR" );
28
28
}
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
+ }
29
74
}
30
- // {{end:logback}}
31
75
0 commit comments