summaryrefslogtreecommitdiff
path: root/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitor.java
blob: 2b99289cd1fac2c423961e46a6038d34e8ed64e2 (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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.qpid.util;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.LinkedList;
import java.util.List;

/**
 * Utility to simplify the monitoring of Log4j file output
 *
 * Monitoring of a given log file can be done alternatively the Monitor will
 * add a new log4j FileAppender to the root Logger to gather all the available
 * logging for monitoring
 */
public class LogMonitor
{
    // The file that the log statements will be written to.
    private final File _logfile;

    // The appender we added to the get messages
    private final FileAppender _appender;

    private int _linesToSkip = 0;

    /**
     * Create a new LogMonitor that creates a new Log4j Appender and monitors
     * all log4j output via the current configuration.
     *
     * @throws IOException if there is a problem creating the temporary file.
     */
    public LogMonitor() throws IOException
    {
        this(null);
    }

    /**
     * Create a new LogMonitor on the specified file if the file does not exist
     * or the value is null then a new Log4j appender will be added and
     * monitoring set up on that appender.
     *
     * NOTE: for the appender to receive any value the RootLogger will need to
     * have the level correctly configured.ng
     *
     * @param file the file to monitor
     *
     * @throws IOException if there is a problem creating a temporary file
     */
    public LogMonitor(File file) throws IOException
    {
        if (file != null && file.exists())
        {
            _logfile = file;
            _appender = null;
        }
        else
        {
            // This is mostly for running the test outside of the ant setup
            _logfile = File.createTempFile("LogMonitor", ".log");
            _appender = new FileAppender(new SimpleLayout(),
                                                     _logfile.getAbsolutePath());
            _appender.setFile(_logfile.getAbsolutePath());
            _appender.setImmediateFlush(true);
            Logger.getRootLogger().addAppender(_appender);
        }
    }

    /**
     * Checks the log file for a given message to appear and returns all
     * instances of that appearance.
     *
     * @param message the message to wait for in the log
     * @param wait    the time in ms to wait for the message to occur
     * @return true if the message was found
     *
     * @throws java.io.FileNotFoundException if the Log file can no longer be found
     * @throws IOException                   thrown when reading the log file
     */
    public List<String> waitAndFindMatches(String message, long wait)
            throws FileNotFoundException, IOException
    {
        if (waitForMessage(message, wait))
        {
            return findMatches(message);
        }
        else
        {
            return new LinkedList<String>();
        }
    }

    /**
     * Checks the log for instances of the search string. If the caller
     * has previously called {@link #markDiscardPoint()}, lines up until the discard
     * point are not considered.
     *
     * The pattern parameter can take any valid argument used in String.contains()
     *
     * {@see String.contains(CharSequences)}
     *
     * @param pattern the search string
     *
     * @return a list of matching lines from the log
     *
     * @throws IOException if there is a problem with the file
     */
    public List<String> findMatches(String pattern) throws IOException
    {

        List<String> results = new LinkedList<String>();

        LineNumberReader reader = new LineNumberReader(new FileReader(_logfile));
        try
        {
            while (reader.ready())
            {
                String line = reader.readLine();
                if (reader.getLineNumber()  > _linesToSkip && line.contains(pattern))
                {
                    results.add(line);
                }
            }
        }
        finally
        {
            reader.close();
        }

        return results;
    }

    /**
     * Checks the log file for a given message to appear.  If the caller
     * has previously called {@link #markDiscardPoint()}, lines up until the discard
     * point are not considered.
     *
     * @param message the message to wait for in the log
     * @param wait    the time in ms to wait for the message to occur
     * @return true if the message was found
     *
     * @throws java.io.FileNotFoundException if the Log file can no longer be found
     * @throws IOException                   thrown when reading the log file
     */
    public boolean waitForMessage(String message, long wait)
            throws FileNotFoundException, IOException
    {
        // Loop through alerts until we're done or wait ms seconds have passed,
        // just in case the logfile takes a while to flush.
        LineNumberReader reader = null;
        try
        {
            reader = new LineNumberReader(new FileReader(_logfile));

            boolean found = false;
            long endtime = System.currentTimeMillis() + wait;
            while (!found && System.currentTimeMillis() < endtime)
            {
                boolean ready = true;
                while (ready = reader.ready())
                {
                    String line = reader.readLine();

                    if (reader.getLineNumber() > _linesToSkip)
                    {
                        if (line.contains(message))
                        {
                            found = true;
                            break;
                        }
                    }
                }
                if (!ready)
                {
                    try
                    {
                        Thread.sleep(50);
                    }
                    catch (InterruptedException ie)
                    {
                        Thread.currentThread().interrupt();
                    }
                }
            }
            return found;

        }
        finally
        {
            if (reader != null)
            {
                reader.close();
            }
        }
    }
    
    /**
     * Read the log file in to memory as a String
     *
     * @return the current contents of the log file
     *
     * @throws java.io.FileNotFoundException if the Log file can no longer be found
     * @throws IOException                   thrown when reading the log file
     */
    public String readFile() throws FileNotFoundException, IOException
    {
        return FileUtils.readFileAsString(_logfile);
    }

    /**
     * Return a File reference to the monitored file
     *
     * @return the file being monitored
     */
    public File getMonitoredFile()
    {
        return _logfile;
    }

    /**
     * Marks the discard point in the log file.
     *
     * @throws java.io.FileNotFoundException if the Log file can no longer be found
     * @throws IOException                   thrown if there is a problem with the log file
     */
    public void markDiscardPoint() throws FileNotFoundException, IOException
    {
        _linesToSkip = countLinesInFile();
    }

    private int countLinesInFile() throws IOException
    {
        int lineCount = 0;
        BufferedReader br = null;
        try
        {
            br = new BufferedReader(new FileReader(_logfile));
            while(br.readLine() != null)
            {
                lineCount++;
            }

            return lineCount;
        }
        finally
        {
            if (br != null)
            {
                br.close();
            }
        }
    }

    /**
     * Stop monitoring this file.
     *
     * This is required to be called incase we added a new logger.
     *
     * If we don't call close then the new logger will continue to get log entries
     * after our desired test has finished.
     */
    public void close()
    {
        //Remove the custom appender we added for this logger
        if (_appender != null)
        {
            Logger.getRootLogger().removeAppender(_appender);
        }
    }

}