Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (c) 2004, 2010 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html Contributors: IBM Corporation - initial API and implementation /
 
 package org.eclipse.core.runtime.adaptor;
 
 import java.io.*;
 import java.util.Date;
The FrameworkLog implementation for Eclipse.

Clients may extend this class.

Since:
3.1
 
 public class EclipseLog implements FrameworkLog {
 	private static final String PASSWORD = "-password"//$NON-NLS-1$	
 	
The session tag
 
 	protected static final String SESSION = "!SESSION"//$NON-NLS-1$
 	
The entry tag
 
 	protected static final String ENTRY = "!ENTRY"//$NON-NLS-1$
 	
The sub-entry tag
 
 	protected static final String SUBENTRY = "!SUBENTRY"//$NON-NLS-1$
 	
The message tag
 
 	protected static final String MESSAGE = "!MESSAGE"//$NON-NLS-1$
 	
The stacktrace tag
 
 	protected static final String STACK = "!STACK"//$NON-NLS-1$
 
The line separator used in the log output
 
 	protected static final String LINE_SEPARATOR;
The tab character used in the log output
 
 	protected static final String TAB_STRING = "\t"//$NON-NLS-1$
 
 	//Constants for rotating log file
 	
The default size a log file can grow before it is rotated
 
 	public static final int DEFAULT_LOG_SIZE = 1000;
The default number of backup log files
 
 	public static final int DEFAULT_LOG_FILES = 10;
The minimum size limit for log rotation
 
 	public static final int LOG_SIZE_MIN = 10;

The system property used to specify the log level
 
 	public static final String PROP_LOG_LEVEL = "eclipse.log.level"//$NON-NLS-1$
 	
The system property used to specify size a log file can grow before it is rotated
 
 	public static final String PROP_LOG_SIZE_MAX = "eclipse.log.size.max"//$NON-NLS-1$
 	
The system property used to specify the maximim number of backup log files to use
 
 	public static final String PROP_LOG_FILE_MAX = "eclipse.log.backup.max"//$NON-NLS-1$
 	
The extension used for log files
 
 	public static final String LOG_EXT = ".log"//$NON-NLS-1$
 	
The extension markup to use for backup log file
 
 	public static final String BACKUP_MARK = ".bak_"//$NON-NLS-1$
 
 	static {
 		String s = System.getProperty("line.separator"); //$NON-NLS-1$
 		 = s == null ? "\n" : s//$NON-NLS-1$
 	}
 	private static final SecureAction secureAction = (SecureAction) AccessController.doPrivileged(SecureAction.createSecureAction());

Indicates if the console messages should be printed to the console (System.out)
 
 	protected boolean consoleLog = false;
Indicates if the next log message is part of a new session
 
 	protected boolean newSession = true;
The File object to store messages. This value may be null.
 
 	protected File outFile;

The Writer to log messages to.
 
 	protected Writer writer;
 
 	int maxLogSize = // The value is in KB.
 	int backupIdx = 0;
 
 	private int logLevel = .;

Constructs an EclipseLog which uses the specified File to log messages to

Parameters:
outFile a file to log messages to
 
 	public EclipseLog(File outFile) {
		this. = outFile;
		this. = null;
	}

Constructs an EclipseLog which uses the specified Writer to log messages to

Parameters:
writer a writer to log messages to
	public EclipseLog(Writer writer) {
		if (writer == null)
			// log to System.err by default
		else
			this. = writer;
	}

Constructs an EclipseLog which uses System.err to write log messages to
	public EclipseLog() {
		this((Writernull);
	}
	private Throwable getRoot(Throwable t) {
		Throwable root = null;
		if (t instanceof BundleException)
		if (t instanceof InvocationTargetException)
		// skip inner InvocationTargetExceptions and BundleExceptions
		if (root instanceof InvocationTargetException || root instanceof BundleException) {
			Throwable deeplyNested = getRoot(root);
			if (deeplyNested != null)
				// if we have something more specific, use it, otherwise keep what we have
				root = deeplyNested;
		}
		return root;
	}

Helper method for writing out argument arrays.

Parameters:
header the header
args the list of arguments
	protected void writeArgs(String headerString[] argsthrows IOException {
		if (args == null || args.length == 0)
			return;
		write(header);
		for (int i = 0; i < args.lengthi++) {
			//mask out the password argument for security
			if (i > 0 && .equals(args[i - 1]))
				write(" (omitted)"); //$NON-NLS-1$
			else
				write(" " + args[i]); //$NON-NLS-1$
		}
	}

Returns the session timestamp. This is the time the platform was started

Returns:
the session timestamp
	protected String getSessionTimestamp() {
		// Main should have set the session start-up timestamp so return that. 
		// Return the "now" time if not available.
		String ts = FrameworkProperties.getProperty("eclipse.startTime"); //$NON-NLS-1$
		if (ts != null) {
			try {
				return getDate(new Date(Long.parseLong(ts)));
catch (NumberFormatException e) {
				// fall through and use the timestamp from right now
			}
		}
		return getDate(new Date());
	}

Writes the session

Throws:
java.io.IOException if an error occurs writing to the log
	protected void writeSession() throws IOException {
		write(date);
		for (int i = .length() + date.length(); i < 78; i++) {
			write("-"); //$NON-NLS-1$
		}
		// Write out certain values found in System.getProperties()
		try {
			String key = "eclipse.buildId"//$NON-NLS-1$
			String value = FrameworkProperties.getProperty(key"unknown"); //$NON-NLS-1$
			writeln(key + "=" + value); //$NON-NLS-1$
			key = "java.fullversion"//$NON-NLS-1$
			value = System.getProperty(key);
			if (value == null) {
				key = "java.version"//$NON-NLS-1$
				value = System.getProperty(key);
				writeln(key + "=" + value); //$NON-NLS-1$
				key = "java.vendor"//$NON-NLS-1$
				value = System.getProperty(key);
				writeln(key + "=" + value); //$NON-NLS-1$
else {
				writeln(key + "=" + value); //$NON-NLS-1$
			}
catch (Exception e) {
			// If we're not allowed to get the values of these properties
			// then just skip over them.
		}
		// The Bootloader has some information that we might be interested in.
		write("BootLoader constants: OS=" + EclipseEnvironmentInfo.getDefault().getOS()); //$NON-NLS-1$
		write(", ARCH=" + EclipseEnvironmentInfo.getDefault().getOSArch()); //$NON-NLS-1$
		write(", WS=" + EclipseEnvironmentInfo.getDefault().getWS()); //$NON-NLS-1$
		writeln(", NL=" + EclipseEnvironmentInfo.getDefault().getNL()); //$NON-NLS-1$
		// Add the command-line arguments used to invoke the platform 
		// XXX: this includes runtime-private arguments - should we do that?
		writeArgs("Framework arguments: ", EclipseEnvironmentInfo.getDefault().getNonFrameworkArgs()); //$NON-NLS-1$
		writeArgs("Command-line arguments: ", EclipseEnvironmentInfo.getDefault().getCommandLineArgs()); //$NON-NLS-1$
	}
	public void close() {
		try {
			if ( != null) {
				Writer tmpWriter = ;
				 = null;
				tmpWriter.close();
			}
catch (IOException e) {
		}
	}

If a File is used to log messages to then the File opened and a Writer is created to log messages to.
	protected void openFile() {
		if ( == null) {
			if ( != null) {
				try {
catch (IOException e) {
				}
else {
			}
		}
	}

If a File is used to log messages to then the writer is closed.
	protected void closeFile() {
		if ( != null) {
			if ( != null) {
				try {
catch (IOException e) {
					// we cannot log here; just print the stacktrace.
				}
				 = null;
			}
		}
	}
	public void log(FrameworkEvent frameworkEvent) {
		Bundle b = frameworkEvent.getBundle();
		Throwable t = frameworkEvent.getThrowable();
		String entry = b.getSymbolicName() == null ? b.getLocation() : b.getSymbolicName();
		int severity;
		switch (frameworkEvent.getType()) {
				severity = .;
				break;
				break;
				break;
			default :
				severity = .;
		}
		FrameworkLogEntry logEntry = new FrameworkLogEntry(entryseverity, 0, "", 0, tnull); //$NON-NLS-1$
		log(logEntry);
	}
	public synchronized void log(FrameworkLogEntry logEntry) {
		if (logEntry == null)
			return;
		if (!isLoggable(logEntry))
			return;
		try {
			if () {
				 = false;
			}
			writeLog(0, logEntry);
catch (Exception e) {
			// any exceptions during logging should be caught 
			..println("An exception occurred while writing to the platform log:");//$NON-NLS-1$
			..println("Logging to the console instead.");//$NON-NLS-1$
			//we failed to write, so dump log entry to console instead
			try {
				writeLog(0, logEntry);
catch (Exception e2) {
				..println("An exception occurred while logging to the console:");//$NON-NLS-1$
			}
finally {
		}
	}
	public synchronized void setWriter(Writer newWriterboolean append) {
		setOutput(nullnewWriterappend);
	}
	public synchronized void setFile(File newFileboolean appendthrows IOException {
		if (newFile != null && !newFile.equals(this.)) {
			// If it's a new file, then reset.
			 = 0;
		}
		setOutput(newFilenullappend);
		FrameworkProperties.setProperty(.newFile == null ? "" : newFile.getAbsolutePath()); //$NON-NLS-1$
	}
	public synchronized File getFile() {
		return ;
	}
	public void setConsoleLog(boolean consoleLog) {
		this. = consoleLog;
	}
	private void setOutput(File newOutFileWriter newWriterboolean append) {
		if (newOutFile == null || !newOutFile.equals(this.)) {
			if (this. != null) {
				try {
					this..close();
catch (IOException e) {
				}
				this. = null;
			}
			// Append old outFile to newWriter. We only attempt to do this
			// if the current Writer is backed by a File and this is not
			// a new session.
			File oldOutFile = this.;
			this. = newOutFile;
			this. = newWriter;
			boolean copyFailed = false;
			if (append && oldOutFile != null && oldOutFile.isFile()) {
				Reader fileIn = null;
				try {
					fileIn = new InputStreamReader(.getFileInputStream(oldOutFile), "UTF-8"); //$NON-NLS-1$
					copyReader(fileInthis.);
catch (IOException e) {
					copyFailed = true;
finally {
					if (fileIn != null) {
						try {
							fileIn.close();
catch (IOException e) {
						}
						// delete the old file if copying didn't fail
						if (!copyFailed)
							oldOutFile.delete();
					}
				}
			}
		}
	}
	private void copyReader(Reader readerWriter aWriterthrows IOException {
		char buffer[] = new char[1024];
		int count;
		while ((count = reader.read(buffer, 0, buffer.length)) > 0) {
			aWriter.write(buffer, 0, count);
		}
	}

Returns a date string using the correct format for the log.

Parameters:
date the Date to format
Returns:
a date string.
	protected String getDate(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		StringBuffer sb = new StringBuffer();
		appendPaddedInt(c.get(.) + 1, 2, sb).append('-');
		return sb.toString();
	}
	private StringBuffer appendPaddedInt(int valueint padStringBuffer buffer) {
		pad = pad - 1;
		if (pad == 0)
			return buffer.append(Integer.toString(value));
		int padding = (int) Math.pow(10, pad);
		if (value >= padding)
			return buffer.append(Integer.toString(value));
		while (padding > value && padding > 1) {
			buffer.append('0');
			padding = padding / 10;
		}
		buffer.append(value);
		return buffer;
	}

Returns a stacktrace string using the correct format for the log

Parameters:
t the Throwable to get the stacktrace for
Returns:
a stacktrace string
	protected String getStackTrace(Throwable t) {
		if (t == null)
			return null;
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		// ensure the root exception is fully logged
		Throwable root = getRoot(t);
		if (root != null) {
			pw.println("Root exception:"); //$NON-NLS-1$
		}
		return sw.toString();
	}

Returns a Writer for the given OutputStream

Parameters:
output an OutputStream to use for the Writer
Returns:
a Writer for the given OutputStream
	protected Writer logForStream(OutputStream output) {
		try {
			return new BufferedWriter(new OutputStreamWriter(output"UTF-8")); //$NON-NLS-1$
			return new BufferedWriter(new OutputStreamWriter(output));
		}
	}

Writes the log entry to the log using the specified depth. A depth value of 0 idicates that the log entry is the root entry. Any value greater than 0 indicates a sub-entry.

Parameters:
depth the depth of th entry
entry the entry to log
Throws:
java.io.IOException if any error occurs writing to the log
	protected void writeLog(int depthFrameworkLogEntry entrythrows IOException {
		writeEntry(depthentry);
		writeStack(entry);
		FrameworkLogEntry[] children = entry.getChildren();
		if (children != null) {
			for (int i = 0; i < children.lengthi++) {
				writeLog(depth + 1, children[i]);
			}
		}
	}

Writes the ENTRY or SUBENTRY header for an entry. A depth value of 0 indicates that the log entry is the root entry. Any value greater than 0 indicates a sub-entry.

Parameters:
depth the depth of th entry
entry the entry to write the header for
Throws:
java.io.IOException if any error occurs writing to the log
	protected void writeEntry(int depthFrameworkLogEntry entrythrows IOException {
		if (depth == 0) {
			writeln(); // write a blank line before all !ENTRY tags bug #64406
else {
			write(Integer.toString(depth));
		}
		write(entry.getEntry());
		write(Integer.toString(entry.getSeverity()));
		write(Integer.toString(entry.getBundleCode()));
		write(getDate(new Date()));
	}

Writes the MESSAGE header to the log for the given entry.

Parameters:
entry the entry to write the message for
Throws:
java.io.IOException if any error occurs writing to the log
	protected void writeMessage(FrameworkLogEntry entrythrows IOException {
	}

Writes the STACK header to the log for the given entry.

Parameters:
entry the entry to write the stacktrace for
Throws:
java.io.IOException if any error occurs writing to the log
	protected void writeStack(FrameworkLogEntry entrythrows IOException {
		Throwable t = entry.getThrowable();
		if (t != null) {
			String stack = getStackTrace(t);
			write(Integer.toString(entry.getStackCode()));
			write(stack);
		}
	}

Writes the given message to the log.

Parameters:
message the message
Throws:
java.io.IOException if any error occurs writing to the log
	protected void write(String messagethrows IOException {
		if (message != null) {
			.write(message);
				..print(message);
		}
	}

Writes the given message to the log and a newline.

Parameters:
s the message
Throws:
java.io.IOException if any error occurs writing to the log
	protected void writeln(String sthrows IOException {
	}

Writes a newline log.

Throws:
java.io.IOException if any error occurs writing to the log
	protected void writeln() throws IOException {
	}

Writes a space to the log.

Throws:
java.io.IOException if any error occurs writing to the log
	protected void writeSpace() throws IOException {
		write(" "); //$NON-NLS-1$
	}

Checks the log file size. If the log file size reaches the limit then the log is rotated

Returns:
false if an error occured trying to rotate the log
	protected boolean checkLogFileSize() {
		if ( == 0)
			return true// no size limitation.
		boolean isBackupOK = true;
		if ( != null) {
			if ((.length() >> 10) > ) { // Use KB as file size unit.
				String logFilename = .getAbsolutePath();
				// Delete old backup file that will be replaced.
				String backupFilename = ""//$NON-NLS-1$
				if (logFilename.toLowerCase().endsWith()) {
					backupFilename = logFilename.substring(0, logFilename.length() - .length()) +  +  + ;
else {
					backupFilename = logFilename +  + ;
				}
				File backupFile = new File(backupFilename);
				if (backupFile.exists()) {
					if (!backupFile.delete()) {
						..println("Error when trying to delete old log file: " + backupFile.getName());//$NON-NLS-1$ 
						if (backupFile.renameTo(new File(backupFile.getAbsolutePath() + System.currentTimeMillis()))) {
							..println("So we rename it to filename: " + backupFile.getName()); //$NON-NLS-1$
else {
							..println("And we also cannot rename it!"); //$NON-NLS-1$
							isBackupOK = false;
						}
					}
				}
				// Rename current log file to backup one.
				boolean isRenameOK = .renameTo(backupFile);
				if (!isRenameOK) {
					..println("Error when trying to rename log file to backup one."); //$NON-NLS-1$
					isBackupOK = false;
				}
				File newFile = new File(logFilename);
				setOutput(newFilenullfalse);
				// Write a new SESSION header to new log file.
				try {
					writeln("This is a continuation of log file " + backupFile.getAbsolutePath());//$NON-NLS-1$
					writeln("Created Time: " + getDate(new Date(System.currentTimeMillis()))); //$NON-NLS-1$
catch (IOException ioe) {
				}
			}
		}
		return isBackupOK;
	}

Reads the PROP_LOG_SIZE_MAX and PROP_LOG_FILE_MAX properties.
	protected void readLogProperties() {
		if (newMaxLogSize != null) {
			 = Integer.parseInt(newMaxLogSize);
			if ( != 0 &&  < ) {
				// If the value is '0', then it means no size limitation.
				// Also, make sure no inappropriate(too small) assigned value.
			}
		}
		if (newMaxLogFiles != null) {
			 = Integer.parseInt(newMaxLogFiles);
			if ( < 1) {
				// Make sure no invalid assigned value. (at least >= 1)
			}
		}
		if (newLogLevel != null) {
			if (newLogLevel.equals("ERROR")) //$NON-NLS-1$
			else if (newLogLevel.equals("WARNING")) //$NON-NLS-1$
			else if (newLogLevel.equals("INFO")) //$NON-NLS-1$
			else
				 = .// OK (0) means log everything
		}
	}

Determines if the log entry should be logged based on log level.
	private boolean isLoggable(FrameworkLogEntry entry) {
		if ( == 0)
			return true;
		return (entry.getSeverity() & ) != 0;
	}
New to GrepCode? Check out our FAQ X