1 /*
2 * EL4J, the Extension Library for the J2EE, adds incremental enhancements to
3 * the spring framework, http://el4j.sf.net
4 * Copyright (C) 2009 by ELCA Informatique SA, Av. de la Harpe 22-24,
5 * 1000 Lausanne, Switzerland, http://www.elca.ch
6 *
7 * EL4J is published under the GNU Lesser General Public License (LGPL)
8 * Version 2.1. See http://www.gnu.org/licenses/
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Lesser General Public License for more details.
14 *
15 * For alternative licensing, please contact info@elca.ch
16 */
17 package ch.elca.el4j.util.socketstatistics;
18
19 import java.io.IOException;
20 import java.io.OutputStream;
21
22 import ch.elca.el4j.util.socketstatistics.genericlogger.GenericLogFactory;
23 import ch.elca.el4j.util.socketstatistics.genericlogger.GenericLogger;
24
25 /**
26 * Implementation of OutputStream with modification for logging.
27 *
28 * @svnLink $Revision: 3929 $;$Date: 2009-09-25 16:38:41 +0200 (Fr, 25. Sep 2009) $;$Author: jonasha $;$URL: https://el4j.svn.sourceforge.net/svnroot/el4j/branches/el4j_3_1/el4j/framework/modules/socketstatistics/src/main/java/ch/elca/el4j/util/socketstatistics/OutputStreamLogger.java $
29 *
30 * @author Jonas Hauenstein (JHN)
31 */
32 public class OutputStreamLogger extends OutputStream {
33
34 /**
35 * Reference to original OutputStream.
36 */
37 private OutputStream m_os;
38 /**
39 * Reference to ConnectionStatistics for logging.
40 */
41 private ConnectionStatistics m_cs;
42
43 /**
44 * Generic Logger.
45 */
46 private final GenericLogger m_logger = GenericLogFactory.getLogger(SocketStatistics.class);
47
48 /**
49 * Constructor.
50 *
51 * @param os
52 * original OutputStream used for writing
53 * @param cs
54 * ConnectionStatistics used for logging
55 */
56 public OutputStreamLogger(OutputStream os, ConnectionStatistics cs) {
57 this.m_os = os;
58 this.m_cs = cs;
59 }
60
61 /**
62 * Modified version of write which also logs traffic to assigned ConnectionStatistics. {@inheritDoc}
63 */
64 public void write(int b) throws IOException {
65 m_os.write(b);
66 m_cs.addbytessent(1);
67 if (m_logger.isLogEnabled("debug")) {
68 m_logger.log("debug", "SocketID: " + m_cs.getSocketID() + " writes " + (char) b);
69 }
70 }
71
72 /**
73 * Modified version of write which also logs traffic to assigned ConnectionStatistics. {@inheritDoc}
74 */
75 public void write(byte[] b, int off, int length) throws IOException {
76 m_os.write(b, off, length);
77 m_cs.addbytessent(length);
78 if (m_logger.isLogEnabled("debug")) {
79 // create String from response
80 StringBuilder sb = new StringBuilder("SocketID: " + m_cs.getSocketID() + " reads ");
81 for (int i = off; i < off + length; i++) {
82 sb.append((char) b[i]);
83 }
84 m_logger.log("debug", sb.toString());
85 }
86 }
87
88 }