aboutsummaryrefslogtreecommitdiffstats
path: root/utils-test/src/main/java/org/onap/policy/common/utils/test/log/logback/ExtractAppender.java
blob: f012464c24c65c53918a2816b9d9b14493c2062a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/*
 * ============LICENSE_START=======================================================
 * Integrity Audit
 * ================================================================================
 * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * 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.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.common.utils.test.log.logback;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;

/**
 * This is an appender that is intended for use by JUnit tests that wish to
 * capture logged messages. The appender takes an optional list of regular
 * expressions that are used to identify and extract data of interest.
 * <p/>
 * If no patterns are provided, then every logged message is recorded. However,
 * if patterns are provided, then only messages that match one of the patterns
 * are recorded. In addition, if the pattern contains a capture group that is
 * non-null, only the captured group is recorded. Otherwise, the entire portion
 * of the message that matches the pattern is recorded.
 * <p/>
 * All operations are thread-safe.
 */
public class ExtractAppender extends AppenderBase<ILoggingEvent> {

	/**
	 * Extracted text is placed here.
	 */
	private final Queue<String> extracted;

	/**
	 * Regular expressions/Patterns to be used to extract text. Uses a
	 * LinkedHashMap so that order is preserved.
	 */
	private final LinkedHashMap<String, Pattern> patterns;

	/**
	 * Records every message that is logged.
	 */
	public ExtractAppender() {
		this(new LinkedList<>());
	}

	/**
	 * Records portions of messages that match one of the regular expressions.
	 * 
	 * @param regex
	 *            regular expression (i.e., {@link Pattern}) to match
	 */
	public ExtractAppender(String... regex) {
		this(new LinkedList<>(), regex);
	}

	/**
	 * Rather than allocating an internal queue to store matched messages,
	 * messages are recorded in the specified target queue using the
	 * {@link Queue#offer(Object)} method. Note: whenever the queue is used, it
	 * will be synchronized to prevent simultaneous accesses.
	 * 
	 * @param target
	 * @param regex
	 *            regular expression (i.e., {@link Pattern}) to match
	 */
	public ExtractAppender(Queue<String> target, String... regex) {
		extracted = target;
		patterns = new LinkedHashMap<>(regex.length);

		for (String re : regex) {
			patterns.put(re, Pattern.compile(re));
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see ch.qos.logback.core.AppenderBase#append(Object)
	 */
	@Override
	protected void append(ILoggingEvent event) {

		String msg = event.getMessage();

		synchronized (patterns) {
			if (patterns.isEmpty()) {
				addExtraction(msg);
				return;
			}

			for (Pattern p : patterns.values()) {
				Matcher m = p.matcher(msg);

				if (m.find()) {
					addGroupMatch(m);
					break;
				}
			}
		}
	}

	/**
	 * Adds the first match group to {@link #extracted}.
	 * 
	 * @param mat
	 *            the matcher containing the groups
	 * @return {@code true} if a group was found, {@code false} otherwise
	 */
	private void addGroupMatch(Matcher mat) {
		int ngroups = mat.groupCount();

		for (int x = 1; x <= ngroups; ++x) {
			String txt = mat.group(x);

			if (txt != null) {
				addExtraction(txt);
				return;
			}
		}

		addExtraction(mat.group());
	}

	/**
	 * Adds an item to {@link #extracted}, in a thread-safe manner. It uses the
	 * queue's <i>offer()</i> method so that the queue can discard the item if
	 * it so chooses, without generating an exception.
	 * 
	 * @param txt
	 *            text to be added
	 */
	private void addExtraction(String txt) {
		synchronized (extracted) {
			extracted.offer(txt);
		}
	}

	/**
	 * Gets the text that has been extracted.
	 * 
	 * @return a copy of the text that has been extracted
	 */
	public List<String> getExtracted() {
		synchronized (extracted) {
			return new ArrayList<>(extracted);
		}
	}

	/**
	 * Clears the list of extracted text.
	 */
	public void clearExtractions() {
		synchronized (extracted) {
			extracted.clear();
		}
	}

	/**
	 * Adds a pattern to be matched by this appender.
	 * 
	 * @param regex
	 *            regular expression (i.e., {@link Pattern}) to match
	 */
	public void setPattern(String regex) {
		synchronized (patterns) {
			patterns.put(regex, Pattern.compile(regex));
		}
	}

}