1 /*
2 * This file is a part of CAST project.
3 * (c) Copyright 2007, AGH University of Science & Technology
4 * https://caribou.iisg.agh.edu.pl/trac/cast
5 *
6 * Licensed under the Eclipse Public License, Version 1.0 (the "License").
7 * You may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 * http://www.eclipse.org/legal/epl-v10.html
10 */
11 /*
12 * File: LoggingOutputStream.java
13 * Created: 2009-09-02
14 * Author: tmilos
15 * $Id$
16 */
17
18 package pl.edu.agh.cast.util.logging;
19
20 import java.io.ByteArrayOutputStream;
21 import java.io.IOException;
22
23 import org.apache.log4j.Logger;
24 import org.apache.log4j.Priority;
25
26 /**
27 * An output stream that writes contents to a {@link Logger} upon each call to {@link #flush()}.
28 *
29 * @author AGH CAST Team
30 */
31 @SuppressWarnings("nls")
32 public class LoggingOutputStream extends ByteArrayOutputStream {
33
34 private String lineSeparator;
35
36 private Logger logger;
37
38 private Priority priority;
39
40 /**
41 * Constructor.
42 *
43 * @param logger
44 * the logger to write to
45 * @param priority
46 * the priority at which to write the log message
47 */
48 public LoggingOutputStream(Logger logger, Priority priority) {
49 super();
50 this.logger = logger;
51 this.priority = priority;
52 lineSeparator = System.getProperty("line.separator");
53 }
54
55 /**
56 * Writes the existing contents of the output stream to the logger as a log record.
57 *
58 * {@inheritDoc}
59 *
60 * @see java.io.OutputStream#flush()
61 */
62 @Override
63 public void flush() throws IOException {
64
65 String record;
66 synchronized (this) {
67 super.flush();
68 record = this.toString();
69 super.reset();
70
71 if (record.length() == 0 || record.equals(lineSeparator)) {
72 // avoid empty records
73 return;
74 }
75
76 logger.log(priority, record);
77 }
78 }
79
80 }