1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.slf4j;
20
21 import java.util.HashMap;
22 import java.util.Map;
23 import java.util.concurrent.atomic.AtomicReference;
24
25 import org.apache.maven.logging.api.LogLevelRecorder;
26
27
28
29
30 public class DefaultLogLevelRecorder implements LogLevelRecorder {
31 private static final Map<String, Level> ACCEPTED_LEVELS = new HashMap<>();
32
33 static {
34 ACCEPTED_LEVELS.put("WARN", Level.WARN);
35 ACCEPTED_LEVELS.put("WARNING", Level.WARN);
36 ACCEPTED_LEVELS.put("ERROR", Level.ERROR);
37 }
38
39 private Level maxAllowed;
40 private final AtomicReference<Level> maxReached = new AtomicReference<>(Level.DEBUG);
41
42 public DefaultLogLevelRecorder(String threshold) {
43 this(determineThresholdLevel(threshold));
44 }
45
46 public DefaultLogLevelRecorder(Level maxAllowed) {
47 this.maxAllowed = maxAllowed;
48 }
49
50 @Override
51 public boolean hasReachedMaxLevel() {
52 return maxReached.get().ordinal() > maxAllowed.ordinal();
53 }
54
55 @Override
56 public Level getMaxLevelReached() {
57 return maxReached.get();
58 }
59
60 @Override
61 public Level getMaxLevelAllowed() {
62 return maxAllowed;
63 }
64
65 @Override
66 public void setMaxLevelAllowed(Level level) {
67 this.maxAllowed = level;
68 }
69
70 private static Level determineThresholdLevel(String input) {
71 final Level result = ACCEPTED_LEVELS.get(input);
72 if (result == null) {
73 String message = String.format(
74 "%s is not a valid log severity threshold. Valid severities are WARN/WARNING and ERROR.", input);
75 throw new IllegalArgumentException(message);
76 }
77 return result;
78 }
79
80 public void record(org.slf4j.event.Level logLevel) {
81 Level level =
82 switch (logLevel) {
83 case TRACE, DEBUG -> Level.DEBUG;
84 case INFO -> Level.INFO;
85 case WARN -> Level.WARN;
86 case ERROR -> Level.ERROR;
87 };
88 while (true) {
89 Level r = maxReached.get();
90 if (level.ordinal() > r.ordinal()) {
91 if (!maxReached.compareAndSet(r, level)) {
92 continue;
93 }
94 }
95 break;
96 }
97 }
98
99 public boolean metThreshold() {
100 return maxReached.get().ordinal() >= maxAllowed.ordinal();
101 }
102 }