001/* A debug listener that sends messages using Java's Logger API.
002
003 Copyright (c) 1998-2014 The Regents of the University of California.
004 All rights reserved.
005 Permission is hereby granted, without written agreement and without
006 license or royalty fees, to use, copy, modify, and distribute this
007 software and its documentation for any purpose, provided that the above
008 copyright notice and the following two paragraphs appear in all copies
009 of this software.
010
011 IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
012 FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
013 ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
014 THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
015 SUCH DAMAGE.
016
017 THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
018 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
019 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
020 PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
021 CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
022 ENHANCEMENTS, OR MODIFICATIONS.
023
024 PT_COPYRIGHT_VERSION_2
025 COPYRIGHTENDKEY
026
027 */
028package ptolemy.kernel.util;
029
030import java.io.File;
031import java.util.logging.FileHandler;
032import java.util.logging.Level;
033import java.util.logging.Logger;
034import java.util.logging.SimpleFormatter;
035
036///////////////////////////////////////////////////////////////////
037//// LoggerListener
038
039/**
040 A debug listener that sends messages using Java's Logger API.
041
042 @author  Edward A. Lee
043 @version $Id$
044 @since Ptolemy II 10.0
045 @Pt.ProposedRating Yellow (eal)
046 @Pt.AcceptedRating Red (cxh)
047
048 */
049public class LoggerListener implements DebugListener {
050    ///////////////////////////////////////////////////////////////////
051    ////                         constructors                      ////
052
053    /** Create a logger.
054     *  @param name The name for this logger. This should normally be a fully qualified
055     *   classname or full name of the object being listened to.
056     *  @param directory The directory in which to store the log file, or null to use the system temporary directory.
057     *  @param level The logger level.
058     *  @exception IllegalActionException If the log file cannot be opened.
059     */
060    public LoggerListener(String name, File directory, Level level)
061            throws IllegalActionException {
062        _logger = Logger.getLogger(name);
063        _logger.setLevel(level);
064        if (directory != null) {
065            if (!directory.exists()) {
066                // Attempt to create the directory.
067                try {
068                    directory.mkdir();
069                } catch (SecurityException ex) {
070                    throw new IllegalActionException(
071                            "Failed to create directory for log file: "
072                                    + directory.getPath());
073                }
074            }
075            if (!directory.isDirectory()) {
076                throw new IllegalActionException(
077                        "Cannot create directory for log file. There is a file in the way: "
078                                + directory.getPath());
079            }
080            if (!directory.canWrite()) {
081                throw new IllegalActionException(
082                        "Directory for log file is not writable: "
083                                + directory.getPath());
084            }
085        }
086        try {
087            // Use rotating file names, file limit of 1Mbyte, limit of 10 files, append mode.
088            String directoryName = "%t/";
089            if (directory != null) {
090                directoryName = directory.getCanonicalPath();
091                if (!directoryName.endsWith("/")) {
092                    directoryName += "/";
093                }
094            }
095            String filename = directoryName + name + "%g.log";
096
097            // To prevent logs from going to the console.
098            _logger.setUseParentHandlers(false);
099            _handler = new FileHandler(filename, 1000000, 10, false);
100
101            // Lamely, creating a FileHandler is useless without a formatter.
102            SimpleFormatter formatter = new SimpleFormatter();
103            _handler.setFormatter(formatter);
104
105            _logger.addHandler(_handler);
106
107            _logger.log(Level.INFO, "******* Starting new log for " + name);
108        } catch (Exception e) {
109            throw new IllegalActionException(null, e,
110                    "Failed to open log file: " + name);
111        }
112    }
113
114    /** Create a logger.
115     *  This constructor creates a logger that logs all messages,
116     *  and stores the log in system temporary directory (where ever that is).
117     *  @param name The name for this logger. This should normally be a fully qualified
118     *   classname or full name of the object being listened to.
119     *  @param directory The directory in which to store the log file, or null to use the system temporary directory.
120     *  @exception IllegalActionException If the log file cannot be opened.
121     */
122    public LoggerListener(String name, File directory)
123            throws IllegalActionException {
124        this(name, directory, Level.ALL);
125    }
126
127    /** Create a logger.
128     *  This constructor creates a logger that logs all messages,
129     *  and stores the log in system temporary directory (whereever that is).
130     *  @param name The name for this logger. This should normally be a fully qualified
131     *   classname or full name of the object being listened to.
132     *  @exception IllegalActionException If the log file cannot be opened.
133     */
134    public LoggerListener(String name) throws IllegalActionException {
135        this(name, null, Level.ALL);
136    }
137
138    ///////////////////////////////////////////////////////////////////
139    ////                         public methods                    ////
140
141    /** Close the file handler.
142     */
143    public void close() {
144        _handler.close();
145    }
146
147    /** Send a string representation of the event to the log.
148     *  @param event The event.
149     */
150    @Override
151    public void event(DebugEvent event) {
152        _logger.log(Level.INFO, event.toString());
153    }
154
155    /** Send the message to the log.
156     *  @param level The level of the message.
157     *  @param message The message.
158     */
159    public void log(Level level, String message) {
160        _logger.log(level, message);
161    }
162
163    /** Send the message to the log.
164     *  @param message The message.
165     */
166    @Override
167    public void message(String message) {
168        _logger.log(Level.INFO, message);
169    }
170
171    ///////////////////////////////////////////////////////////////////
172    ////                         private variables                 ////
173
174    /** The file handler. */
175    private FileHandler _handler;
176
177    /** The logger. */
178    private Logger _logger;
179}