01: /*
02: * Copyright (C) The Apache Software Foundation. All rights reserved.
03: *
04: * This software is published under the terms of the Apache Software License
05: * version 1.1, a copy of which has been included with this distribution in
06: * the LICENSE file.
07: */
08: package org.jivesoftware.util.log.output.io.rotate;
09:
10: import org.jivesoftware.util.log.format.Formatter;
11: import org.jivesoftware.util.log.output.io.FileTarget;
12: import java.io.File;
13: import java.io.IOException;
14:
15: /**
16: * This is a basic Output log target that writes to rotating files.
17: *
18: * @author <a href="mailto:peter@apache.org">Peter Donald</a>
19: * @author <a href="mailto:mcconnell@osm.net">Stephen McConnell</a>
20: * @author <a href="mailto:bh22351@i-one.at">Bernhard Huber</a>
21: */
22: public class RotatingFileTarget extends FileTarget {
23:
24: ///The rotation strategy to be used.
25: private RotateStrategy m_rotateStrategy;
26:
27: ///The file strategy to be used.
28: private FileStrategy m_fileStrategy;
29:
30: /**
31: * Construct RotatingFileTarget object.
32: *
33: * @param formatter Formatter to be used
34: */
35: public RotatingFileTarget(final Formatter formatter,
36: final RotateStrategy rotateStrategy,
37: final FileStrategy fileStrategy) throws IOException {
38: super (null, false, formatter);
39:
40: m_rotateStrategy = rotateStrategy;
41: m_fileStrategy = fileStrategy;
42:
43: getInitialFile();
44: }
45:
46: public synchronized void rotate() throws IOException {
47: close();
48:
49: final File file = m_fileStrategy.nextFile();
50: setFile(file, false);
51: openFile();
52: }
53:
54: /**
55: * Output the log message, and check if rotation is needed.
56: */
57: public synchronized void write(final String data) {
58: // send the log message
59: super .write(data);
60:
61: // if rotation is needed, close old File, create new File
62: final boolean rotate = m_rotateStrategy.isRotationNeeded(data,
63: getFile());
64: if (rotate) {
65: try {
66: rotate();
67: } catch (final IOException ioe) {
68: getErrorHandler().error("Error rotating file", ioe,
69: null);
70: }
71: }
72: }
73:
74: private void getInitialFile() throws IOException {
75: close();
76:
77: boolean rotate = m_rotateStrategy.isRotationNeeded("",
78: m_fileStrategy.currentFile());
79:
80: if (rotate) {
81: setFile(m_fileStrategy.nextFile(), false);
82: } else {
83: setFile(m_fileStrategy.currentFile(), true);
84: }
85:
86: openFile();
87: }
88: }
|