mirror of
https://github.com/ebean-orm/ebean.git
synced 2026-11-18 14:58:47 +00:00
Refactor transaction logging to simple SLF4J use
This commit is contained in:
1 parent
b5ef07bab9
commit
cbd7b5e912
60 files changed
+2976
-4529
No files matched your search
@@ -5,13 +5,16 @@ import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.persistence.RollbackException;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.avaje.ebean.LogLevel;
|
||||
import com.avaje.ebean.bean.PersistenceContext;
|
||||
import com.avaje.ebeaninternal.api.DerivedRelationshipData;
|
||||
@@ -19,8 +22,6 @@ import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
import com.avaje.ebeaninternal.api.TransactionEvent;
|
||||
import com.avaje.ebeaninternal.server.persist.BatchControl;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionManager.OnQueryOnly;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* JDBC Connection based transaction.
|
||||
@@ -29,6 +30,8 @@ public class JdbcTransaction implements SpiTransaction {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(JdbcTransaction.class);
|
||||
|
||||
private static final Object PLACEHOLDER = new Object();
|
||||
|
||||
private static final String illegalStateMessage = "Transaction is Inactive";
|
||||
|
||||
/**
|
||||
@@ -110,20 +113,18 @@ public class JdbcTransaction implements SpiTransaction {
|
||||
|
||||
Boolean batchFlushOnMixed;
|
||||
|
||||
String logPrefix;
|
||||
|
||||
/**
|
||||
* The depth used by batch processing to help the ordering of statements.
|
||||
*/
|
||||
int depth = 0;
|
||||
|
||||
HashSet<Object> persistingBeans = new HashSet<Object>();
|
||||
IdentityHashMap<Object,Object> persistingBeans;
|
||||
HashSet<Integer> deletingBeansHash;
|
||||
HashMap<String,String> m2mIntersectionSave;
|
||||
|
||||
TransactionLogBuffer logBuffer;
|
||||
|
||||
HashMap<Integer, List<DerivedRelationshipData>> derivedRelMap;
|
||||
|
||||
private final Map<String, Object> userObjects = new ConcurrentHashMap<String, Object>();
|
||||
Map<String, Object> userObjects;
|
||||
|
||||
/**
|
||||
* Create a new JdbcTransaction.
|
||||
@@ -132,6 +133,7 @@ public class JdbcTransaction implements SpiTransaction {
|
||||
try {
|
||||
this.active = true;
|
||||
this.id = id;
|
||||
this.logPrefix = deriveLogPrefix(id,null);
|
||||
this.explicit = explicit;
|
||||
this.logLevel = logLevel;
|
||||
this.manager = manager;
|
||||
@@ -143,15 +145,34 @@ public class JdbcTransaction implements SpiTransaction {
|
||||
this.onQueryOnly = manager == null ? OnQueryOnly.ROLLBACK : manager.getOnQueryOnly();
|
||||
this.persistenceContext = new DefaultPersistenceContext();
|
||||
|
||||
this.logBuffer = new TransactionLogBuffer(50, id);
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new PersistenceException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String deriveLogPrefix(String id, String label) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("txn[");
|
||||
if (id != null) {
|
||||
sb.append(id);
|
||||
}
|
||||
sb.append("] ");
|
||||
if (label != null) {
|
||||
sb.append("label[").append(label).append("] ");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void setLabel(String label) {
|
||||
this.logPrefix = deriveLogPrefix(id,label);
|
||||
}
|
||||
|
||||
public String getLogPrefix() {
|
||||
return logPrefix;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "Trans[" + id + "]";
|
||||
return logPrefix;
|
||||
}
|
||||
|
||||
public List<DerivedRelationshipData> getDerivedRelationship(Object bean) {
|
||||
@@ -215,13 +236,16 @@ public class JdbcTransaction implements SpiTransaction {
|
||||
public void unregisterBean(Object bean) {
|
||||
persistingBeans.remove(bean);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Return true if this is a bean that has already been saved. This will
|
||||
* register the bean if it is not already.
|
||||
*/
|
||||
public boolean isRegisteredBean(Object bean) {
|
||||
return !persistingBeans.add(bean);
|
||||
if (persistingBeans == null) {
|
||||
persistingBeans = new IdentityHashMap<Object,Object>();
|
||||
}
|
||||
return (persistingBeans.put(bean,PLACEHOLDER) != null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -447,11 +471,11 @@ public class JdbcTransaction implements SpiTransaction {
|
||||
}
|
||||
|
||||
public boolean isLogSql() {
|
||||
return logLevel.ordinal() >= LogLevel.SQL.ordinal();
|
||||
return TransactionManager.SQL_LOGGER.isDebugEnabled();
|
||||
}
|
||||
|
||||
public boolean isLogSummary() {
|
||||
return logLevel.ordinal() >= LogLevel.SUMMARY.ordinal();
|
||||
return TransactionManager.SUM_LOGGER.isDebugEnabled();
|
||||
}
|
||||
|
||||
public LogLevel getLogLevel() {
|
||||
@@ -461,28 +485,13 @@ public class JdbcTransaction implements SpiTransaction {
|
||||
public void setLogLevel(LogLevel logLevel) {
|
||||
this.logLevel = logLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a message to the transaction log - for PUBLIC use.
|
||||
*/
|
||||
public void log(String msg) {
|
||||
if (isLogSummary()) {
|
||||
logInternal(msg);
|
||||
}
|
||||
|
||||
public void logSql(String msg) {
|
||||
TransactionManager.SQL_LOGGER.trace(logPrefix+msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a message to the transaction log - for Ebean INTERNAL use. The LogLevel
|
||||
* should be explicitly checked before calling this method.
|
||||
*/
|
||||
public void logInternal(String msg) {
|
||||
if (manager != null) {
|
||||
if (logBuffer.add(msg)) {
|
||||
// buffer full so flush it
|
||||
manager.log(logBuffer);
|
||||
logBuffer = logBuffer.newBuffer();
|
||||
}
|
||||
}
|
||||
|
||||
public void logSummary(String msg) {
|
||||
TransactionManager.SUM_LOGGER.debug(logPrefix+msg);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -538,10 +547,6 @@ public class JdbcTransaction implements SpiTransaction {
|
||||
active = false;
|
||||
}
|
||||
|
||||
public TransactionLogBuffer getLogBuffer() {
|
||||
return logBuffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify the transaction manager.
|
||||
*/
|
||||
@@ -682,10 +687,16 @@ public class JdbcTransaction implements SpiTransaction {
|
||||
}
|
||||
|
||||
public void putUserObject(String name, Object value) {
|
||||
if (userObjects == null) {
|
||||
userObjects = new HashMap<String,Object>();
|
||||
}
|
||||
userObjects.put(name, value);
|
||||
}
|
||||
|
||||
public Object getUserObject(String name) {
|
||||
if (userObjects == null) {
|
||||
return null;
|
||||
}
|
||||
return userObjects.get(name);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Buffer of transaction messages.
|
||||
* <p>
|
||||
* For performance reasons we add all the transaction messages to an instance of
|
||||
* TransactionLogBuffer and then when the buffer is full or the transaction ends
|
||||
* we send the buffer to the transaction manager to log.
|
||||
* </p>
|
||||
*
|
||||
* @author rbygrave
|
||||
*
|
||||
*/
|
||||
public class TransactionLogBuffer {
|
||||
|
||||
private final String transactionId;
|
||||
|
||||
private final ArrayList<LogEntry> buffer;
|
||||
|
||||
private final int maxSize;
|
||||
|
||||
private int currentSize;
|
||||
|
||||
/**
|
||||
* Create the buffer with a maxSize and transaction id.
|
||||
*/
|
||||
public TransactionLogBuffer(int maxSize, String transactionId) {
|
||||
this.maxSize = maxSize;
|
||||
this.transactionId = transactionId;
|
||||
this.buffer = new ArrayList<LogEntry>(maxSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new buffer using the same configuration.
|
||||
*/
|
||||
public TransactionLogBuffer newBuffer() {
|
||||
return new TransactionLogBuffer(maxSize, transactionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the transaction id.
|
||||
*/
|
||||
public String getTransactionId() {
|
||||
return transactionId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a message to the buffer.
|
||||
*/
|
||||
public boolean add(String msg) {
|
||||
buffer.add(new LogEntry(msg));
|
||||
return ++currentSize >= maxSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the buffer is empty.
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return buffer.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all the messages.
|
||||
*/
|
||||
public List<LogEntry> messages() {
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Entry in the buffer.
|
||||
*/
|
||||
public class LogEntry {
|
||||
|
||||
private final long timestamp;
|
||||
private final String msg;
|
||||
|
||||
/**
|
||||
* Construct an entry.
|
||||
*/
|
||||
public LogEntry(String msg) {
|
||||
this.timestamp = System.currentTimeMillis();
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the time the entry was put into the buffer.
|
||||
*/
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the text of the message.
|
||||
*/
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import com.avaje.ebean.config.ServerConfig;
|
||||
import com.avaje.ebeaninternal.server.transaction.log.FileTransactionLoggerWrapper;
|
||||
import com.avaje.ebeaninternal.server.transaction.log.JuliTransactionLogger;
|
||||
|
||||
/**
|
||||
* Manages the transaction logs.
|
||||
*/
|
||||
public class TransactionLogManager {
|
||||
|
||||
private final TransactionLogWriter logWriter;
|
||||
|
||||
/**
|
||||
* Create the TransactionLogger.
|
||||
* <p>
|
||||
* DevNote: This registers a shutdown hook to flush and close the
|
||||
* sharedLogger. Alternate option would be to flush() the log after each
|
||||
* write to the log.
|
||||
* </p>
|
||||
*/
|
||||
public TransactionLogManager(ServerConfig serverConfig) {
|
||||
|
||||
if (serverConfig.isLoggingToJavaLogger()){
|
||||
logWriter = new JuliTransactionLogger();
|
||||
} else {
|
||||
logWriter = new FileTransactionLoggerWrapper(serverConfig);
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
logWriter.shutdown();
|
||||
}
|
||||
|
||||
public void log(TransactionLogBuffer logBuffer) {
|
||||
logWriter.log(logBuffer);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
/**
|
||||
* Write transaction log events to a file or other destination.
|
||||
*/
|
||||
public interface TransactionLogWriter {
|
||||
|
||||
/**
|
||||
* Log all the messages in the buffer.
|
||||
*/
|
||||
public void log(TransactionLogBuffer logBuffer);
|
||||
|
||||
/**
|
||||
* Shutdown the writer.
|
||||
*/
|
||||
public void shutdown();
|
||||
|
||||
}
|
||||
@@ -8,9 +8,11 @@ import java.util.concurrent.atomic.AtomicLong;
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.avaje.ebean.BackgroundExecutor;
|
||||
import com.avaje.ebean.LogLevel;
|
||||
import com.avaje.ebean.TxIsolation;
|
||||
import com.avaje.ebean.config.GlobalProperties;
|
||||
import com.avaje.ebean.config.ServerConfig;
|
||||
import com.avaje.ebean.event.TransactionEventListener;
|
||||
@@ -21,8 +23,6 @@ import com.avaje.ebeaninternal.api.TransactionEventTable.TableIUD;
|
||||
import com.avaje.ebeaninternal.server.cluster.ClusterManager;
|
||||
import com.avaje.ebeaninternal.server.core.BootupClasses;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptorManager;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Manages transactions.
|
||||
@@ -35,6 +35,12 @@ public class TransactionManager {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(TransactionManager.class);
|
||||
|
||||
public static final Logger SQL_LOGGER = LoggerFactory.getLogger("org.avaje.ebean.SQL");
|
||||
|
||||
public static final Logger SUM_LOGGER = LoggerFactory.getLogger("org.avaje.ebean.SUM");
|
||||
|
||||
public static final Logger TXN_LOGGER = LoggerFactory.getLogger("org.avaje.ebean.TXN");
|
||||
|
||||
/**
|
||||
* The behaviour desired when ending a query only transaction.
|
||||
*/
|
||||
@@ -60,11 +66,6 @@ public class TransactionManager {
|
||||
|
||||
private LogLevel logLevel;
|
||||
|
||||
/**
|
||||
* The logger.
|
||||
*/
|
||||
private final TransactionLogManager transLogger;
|
||||
|
||||
/**
|
||||
* Prefix for transaction id's (logging).
|
||||
*/
|
||||
@@ -92,7 +93,7 @@ public class TransactionManager {
|
||||
|
||||
private final ClusterManager clusterManager;
|
||||
|
||||
private final int commitDebugLevel;
|
||||
//private final int commitDebugLevel;
|
||||
|
||||
private final String serverName;
|
||||
|
||||
@@ -118,7 +119,6 @@ public class TransactionManager {
|
||||
this.serverName = config.getName();
|
||||
|
||||
this.logLevel = config.getLoggingLevel();
|
||||
this.transLogger = new TransactionLogManager(config);
|
||||
this.backgroundExecutor = backgroundExecutor;
|
||||
this.dataSource = config.getDataSource();
|
||||
this.bulkEventListenerMap = new BulkEventListenerMap(config.getBulkTableEventListeners());
|
||||
@@ -127,7 +127,6 @@ public class TransactionManager {
|
||||
this.transactionEventListeners = transactionEventListeners.toArray(new TransactionEventListener[transactionEventListeners.size()]);
|
||||
|
||||
// log some transaction events using a java util logger
|
||||
this.commitDebugLevel = GlobalProperties.getInt("ebean.commit.debuglevel", 0);
|
||||
this.clusterDebugLevel = GlobalProperties.getInt("ebean.cluster.debuglevel", 0);
|
||||
|
||||
this.defaultBatchMode = config.isPersistBatching();
|
||||
@@ -140,7 +139,7 @@ public class TransactionManager {
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
transLogger.shutdown();
|
||||
// Nothing to do
|
||||
}
|
||||
|
||||
public BeanDescriptorManager getBeanDescriptorManager() {
|
||||
@@ -251,19 +250,6 @@ public class TransactionManager {
|
||||
return onQueryOnly;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the TransactionLogger used by this TransactionManager.
|
||||
*/
|
||||
public TransactionLogManager getLogger() {
|
||||
return transLogger;
|
||||
}
|
||||
|
||||
public void log(TransactionLogBuffer logBuffer){
|
||||
if (!logBuffer.isEmpty()){
|
||||
transLogger.log(logBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap the externally supplied Connection.
|
||||
*/
|
||||
@@ -307,15 +293,6 @@ public class TransactionManager {
|
||||
if (isolationLevel > -1) {
|
||||
c.setTransactionIsolation(isolationLevel);
|
||||
}
|
||||
|
||||
if (commitDebugLevel >= 3){
|
||||
String msg = "Transaction ["+t.getId()+"] begin";
|
||||
if (isolationLevel > -1){
|
||||
TxIsolation txi = TxIsolation.fromLevel(isolationLevel);
|
||||
msg += " isolationLevel["+txi+"]";
|
||||
}
|
||||
logger.info(msg);
|
||||
}
|
||||
|
||||
return t;
|
||||
|
||||
@@ -345,10 +322,6 @@ public class TransactionManager {
|
||||
if (defaultBatchMode){
|
||||
t.setBatchMode(true);
|
||||
}
|
||||
|
||||
if (commitDebugLevel >= 3){
|
||||
logger.info("Transaction ["+t.getId()+"] begin - queryOnly");
|
||||
}
|
||||
|
||||
return t;
|
||||
|
||||
@@ -375,61 +348,30 @@ public class TransactionManager {
|
||||
public void notifyOfRollback(SpiTransaction transaction, Throwable cause) {
|
||||
|
||||
try {
|
||||
for (TransactionEventListener listener : transactionEventListeners) {
|
||||
if (TXN_LOGGER.isInfoEnabled()) {
|
||||
String msg = transaction.getLogPrefix()+"Rollback";
|
||||
if (cause != null){
|
||||
msg += " error: "+formatThrowable(cause);
|
||||
}
|
||||
TXN_LOGGER.info(msg);
|
||||
}
|
||||
|
||||
for (TransactionEventListener listener : transactionEventListeners) {
|
||||
listener.postTransactionRollback(transaction, cause);
|
||||
}
|
||||
|
||||
if (transaction.isLogSummary() || commitDebugLevel >= 1) {
|
||||
String msg = "Rollback";
|
||||
if (cause != null){
|
||||
msg += " error: "+formatThrowable(cause);
|
||||
}
|
||||
if (transaction.isLogSummary()) {
|
||||
transaction.logInternal(msg);
|
||||
}
|
||||
|
||||
if (commitDebugLevel >= 1){
|
||||
logger.info("Transaction ["+transaction.getId()+"] "+msg);
|
||||
}
|
||||
}
|
||||
|
||||
log(transaction.getLogBuffer());
|
||||
} catch (Exception ex) {
|
||||
String m = "Potentially Transaction Log incomplete due to error:";
|
||||
logger.error(m, ex);
|
||||
logger.error("Error while notifying TransactionEventListener of rollback event", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Query only transaction in read committed isolation.
|
||||
*/
|
||||
public void notifyOfQueryOnly(boolean onCommit, SpiTransaction transaction, Throwable cause) {
|
||||
|
||||
try {
|
||||
if (commitDebugLevel >= 2){
|
||||
String msg;
|
||||
if (onCommit){
|
||||
msg = "Commit queryOnly";
|
||||
|
||||
} else {
|
||||
msg = "Rollback queryOnly";
|
||||
if (cause != null){
|
||||
msg += " error: "+formatThrowable(cause);
|
||||
}
|
||||
}
|
||||
if (transaction.isLogSummary()) {
|
||||
transaction.logInternal(msg);
|
||||
}
|
||||
logger.info("Transaction ["+transaction.getId()+"] "+msg);
|
||||
}
|
||||
|
||||
log(transaction.getLogBuffer());
|
||||
|
||||
} catch (Exception ex) {
|
||||
String m = "Potentially Transaction Log incomplete due to error:";
|
||||
logger.error(m, ex);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Query only transaction in read committed isolation.
|
||||
*/
|
||||
public void notifyOfQueryOnly(boolean onCommit, SpiTransaction transaction, Throwable cause) {
|
||||
|
||||
// Nothing that interesting here
|
||||
}
|
||||
|
||||
private String formatThrowable(Throwable e){
|
||||
if (e == null){
|
||||
@@ -461,11 +403,16 @@ public class TransactionManager {
|
||||
public void notifyOfCommit(SpiTransaction transaction) {
|
||||
|
||||
try {
|
||||
|
||||
log(transaction.getLogBuffer());
|
||||
|
||||
PostCommitProcessing postCommit = new PostCommitProcessing(clusterManager, this, transaction,
|
||||
transaction.getEvent());
|
||||
if (transaction.isExplicit()) {
|
||||
if (TXN_LOGGER.isInfoEnabled()) {
|
||||
TXN_LOGGER.info(transaction.getLogPrefix()+"Commit");
|
||||
}
|
||||
} else if (TXN_LOGGER.isDebugEnabled()) {
|
||||
TXN_LOGGER.debug(transaction.getLogPrefix()+"Commit");
|
||||
}
|
||||
|
||||
PostCommitProcessing postCommit = new PostCommitProcessing(clusterManager, this, transaction, transaction.getEvent());
|
||||
|
||||
postCommit.notifyLocalCacheIndex();
|
||||
postCommit.notifyCluster();
|
||||
@@ -476,10 +423,7 @@ public class TransactionManager {
|
||||
for (TransactionEventListener listener : transactionEventListeners) {
|
||||
listener.postTransactionCommit(transaction);
|
||||
}
|
||||
|
||||
if (commitDebugLevel >= 1) {
|
||||
logger.info("Transaction ["+transaction.getId()+"] commit");
|
||||
}
|
||||
|
||||
} catch (Exception ex) {
|
||||
String m = "NotifyOfCommit failed. Cache/Lucene potentially not notified.";
|
||||
logger.error(m, ex);
|
||||
|
||||
-382
@@ -1,382 +0,0 @@
|
||||
package com.avaje.ebeaninternal.server.transaction.log;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintStream;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogBuffer;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogBuffer.LogEntry;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogWriter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Default transaction logger implementation.
|
||||
* <p>
|
||||
* File based logger that can switch daily. It will include the date in the
|
||||
* files name.
|
||||
* </p>
|
||||
* <p>
|
||||
* Administration Note: If log file switching fails it will send the error to
|
||||
* standard out and standard err print streams. This is assumed to be rather
|
||||
* unlikely but possible.
|
||||
* </p>
|
||||
*/
|
||||
public class FileTransactionLogger implements Runnable, TransactionLogWriter {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(FileTransactionLogger.class);
|
||||
|
||||
/**
|
||||
* Used to print stack trace.
|
||||
*/
|
||||
private static final String atString = " at ";
|
||||
|
||||
/**
|
||||
* The newLineChar used instead of NL or CRNL for printing stack traces.
|
||||
*/
|
||||
private final String newLinePlaceholder = "\\r\\n";
|
||||
|
||||
/**
|
||||
* The maximum number of stack lines to output. This is just for transaction
|
||||
* logging so 5 is fine.
|
||||
*/
|
||||
private final int maxStackTraceLines = 5;
|
||||
|
||||
/**
|
||||
* Queue that transactions put their LogBuffers onto and this LogBufferWriter
|
||||
* pulls LogBuffers from.
|
||||
*/
|
||||
private final ConcurrentLinkedQueue<TransactionLogBuffer> logBufferQueue = new ConcurrentLinkedQueue<TransactionLogBuffer>();
|
||||
|
||||
private final Object queueMonitor = new Object();
|
||||
|
||||
/**
|
||||
* Thread that is the sole writer of logBuffer entries to the file.
|
||||
*/
|
||||
private final Thread logWriterThread;
|
||||
|
||||
private final String threadName;
|
||||
|
||||
/**
|
||||
* The path of the log file.
|
||||
*/
|
||||
private final String filepath;
|
||||
|
||||
/**
|
||||
* The delimiter to use.
|
||||
*/
|
||||
private final String deliminator = ", ";
|
||||
|
||||
/**
|
||||
* The prefix of the log file name.
|
||||
*/
|
||||
private final String logFileName;
|
||||
|
||||
/**
|
||||
* The file suffix for the logs.
|
||||
*/
|
||||
private final String logFileSuffix;
|
||||
|
||||
/**
|
||||
* Shutdown flag.
|
||||
*/
|
||||
private volatile boolean shutdown;
|
||||
private volatile boolean shutdownComplete;
|
||||
|
||||
/**
|
||||
* The output stream.
|
||||
*/
|
||||
private PrintStream out;
|
||||
|
||||
/**
|
||||
* The current file path.
|
||||
*/
|
||||
private String currentPath;
|
||||
|
||||
/**
|
||||
* Counter thats incremented when maxBytesPerFile is hit.
|
||||
*/
|
||||
private int fileCounter;
|
||||
|
||||
/**
|
||||
* Roughly the max bytes written to a file before we switch. Switch Daily and
|
||||
* on hitting max bytes.
|
||||
*/
|
||||
private long maxBytesPerFile;
|
||||
|
||||
/**
|
||||
* Roughly the bytes written to a file.
|
||||
*/
|
||||
private long bytesWritten;
|
||||
|
||||
public FileTransactionLogger(String threadName, String dir, String logFileName, int maxBytesPerFile) {
|
||||
this(threadName, dir, logFileName, "log", maxBytesPerFile);
|
||||
}
|
||||
|
||||
public FileTransactionLogger(String threadName, String dir, String logFileName, String suffix, int maxBytesPerFile) {
|
||||
this.threadName = threadName;
|
||||
this.logFileName = logFileName;
|
||||
this.logFileSuffix = "." + suffix;
|
||||
this.maxBytesPerFile = maxBytesPerFile;
|
||||
|
||||
try {
|
||||
// get the directory where the log files are going to go
|
||||
filepath = makeDirIfRequired(dir);
|
||||
|
||||
switchFile(LogTime.nextDay());
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("FATAL ERROR: init of FileLogger: " + e.getMessage());
|
||||
System.err.println("FATAL ERROR: init of FileLogger: " + e.getMessage());
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
logWriterThread = new Thread(this, threadName);
|
||||
logWriterThread.setDaemon(true);
|
||||
}
|
||||
|
||||
protected void finalize() throws Throwable {
|
||||
close();
|
||||
super.finalize();
|
||||
}
|
||||
|
||||
public void start() {
|
||||
logWriterThread.start();
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
|
||||
shutdown = true;
|
||||
|
||||
synchronized (logWriterThread) {
|
||||
try {
|
||||
// wait max 20 seconds
|
||||
logWriterThread.wait(20000);
|
||||
logger.debug("Shutdown LogBufferWriter " + threadName + " shutdownComplete:" + shutdownComplete);
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
logger.debug("InterruptedException:" + e);
|
||||
}
|
||||
}
|
||||
|
||||
if (!shutdownComplete) {
|
||||
String m = "WARNING: Shutdown of LogBufferWriter " + threadName + " not completed.";
|
||||
System.err.println(m);
|
||||
logger.warn(m);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void run() {
|
||||
|
||||
int missCount = 0;
|
||||
|
||||
while (!shutdown || missCount < 10) {
|
||||
if (missCount > 50) {
|
||||
|
||||
if (out != null) {
|
||||
out.flush();
|
||||
}
|
||||
try {
|
||||
Thread.sleep(20);
|
||||
} catch (InterruptedException e) {
|
||||
logger.info("Interrupted TxnLogBufferWriter", e);
|
||||
}
|
||||
}
|
||||
synchronized (queueMonitor) {
|
||||
if (logBufferQueue.isEmpty()) {
|
||||
++missCount;
|
||||
} else {
|
||||
TransactionLogBuffer buffer = logBufferQueue.remove();
|
||||
write(buffer);
|
||||
missCount = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
close();
|
||||
shutdownComplete = true;
|
||||
|
||||
synchronized (logWriterThread) {
|
||||
logWriterThread.notifyAll();
|
||||
}
|
||||
}
|
||||
|
||||
public void log(TransactionLogBuffer logBuffer) {
|
||||
logBufferQueue.add(logBuffer);
|
||||
}
|
||||
|
||||
private void write(TransactionLogBuffer logBuffer) {
|
||||
|
||||
// check to see if we need to switch file?
|
||||
LogTime logTime = LogTime.get();
|
||||
if (logTime.isNextDay()) {
|
||||
logTime = LogTime.nextDay();
|
||||
switchFile(logTime);
|
||||
}
|
||||
|
||||
if (bytesWritten > maxBytesPerFile) {
|
||||
++fileCounter;
|
||||
switchFile(logTime);
|
||||
}
|
||||
|
||||
String txnId = logBuffer.getTransactionId();
|
||||
|
||||
List<LogEntry> messages = logBuffer.messages();
|
||||
for (int i = 0; i < messages.size(); i++) {
|
||||
LogEntry msg = messages.get(i);
|
||||
printMessage(logTime, txnId, msg);
|
||||
}
|
||||
}
|
||||
|
||||
private void printMessage(LogTime logTime, String txnId, LogEntry logEntry) {
|
||||
|
||||
String msg = logEntry.getMsg();
|
||||
int len = msg.length();
|
||||
if (len == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// add overhead + content
|
||||
bytesWritten += 16;
|
||||
bytesWritten += len;
|
||||
|
||||
if (txnId != null) {
|
||||
bytesWritten += 7;
|
||||
bytesWritten += txnId.length();
|
||||
out.append("txn[");
|
||||
out.append(txnId);
|
||||
out.append("]");
|
||||
out.append(deliminator);
|
||||
}
|
||||
|
||||
out.append(logTime.getTimestamp(logEntry.getTimestamp()));
|
||||
out.append(deliminator);
|
||||
out.append(msg).append(" ");
|
||||
out.append("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively output the Throwable stack trace to the log.
|
||||
*
|
||||
* @param sb
|
||||
* the buffer to write the stack trace to
|
||||
* @param e
|
||||
* the source throwable
|
||||
* @param isCause
|
||||
* flag to indicate if this is the top level throwable or a cause
|
||||
*/
|
||||
protected void printThrowable(StringBuilder sb, Throwable e, boolean isCause) {
|
||||
if (e != null) {
|
||||
if (isCause) {
|
||||
sb.append("Caused by: ");
|
||||
}
|
||||
sb.append(e.getClass().getName());
|
||||
sb.append(":");
|
||||
sb.append(e.getMessage()).append(newLinePlaceholder);
|
||||
|
||||
StackTraceElement[] ste = e.getStackTrace();
|
||||
int outputStackLines = ste.length;
|
||||
int notShownCount = 0;
|
||||
if (ste.length > maxStackTraceLines) {
|
||||
outputStackLines = maxStackTraceLines;
|
||||
notShownCount = ste.length - outputStackLines;
|
||||
}
|
||||
for (int i = 0; i < outputStackLines; i++) {
|
||||
sb.append(atString);
|
||||
sb.append(ste[i].toString()).append(newLinePlaceholder);
|
||||
}
|
||||
if (notShownCount > 0) {
|
||||
sb.append(" ... ");
|
||||
sb.append(notShownCount);
|
||||
sb.append(" more").append(newLinePlaceholder);
|
||||
}
|
||||
Throwable cause = e.getCause();
|
||||
if (cause != null) {
|
||||
printThrowable(sb, cause, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String newFileName(LogTime logTime) {
|
||||
return filepath + File.separator + logFileName + logTime.getYMD() + "-" + fileCounter + logFileSuffix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch the file to log to.
|
||||
*/
|
||||
protected void switchFile(LogTime logTime) {
|
||||
|
||||
try {
|
||||
long currentFileLength = 0;
|
||||
String newFilePath = null;
|
||||
|
||||
// skip a file if it already has max bytes
|
||||
do {
|
||||
newFilePath = newFileName(logTime);
|
||||
File f = new File(newFilePath);
|
||||
if (!f.exists()) {
|
||||
currentFileLength = 0;
|
||||
} else {
|
||||
if (f.length() < maxBytesPerFile * 0.8) {
|
||||
currentFileLength = f.length();
|
||||
} else {
|
||||
++fileCounter;
|
||||
newFilePath = null;
|
||||
}
|
||||
}
|
||||
} while (newFilePath == null);
|
||||
|
||||
if (!newFilePath.equals(currentPath)) {
|
||||
PrintStream newOut = new PrintStream(new BufferedOutputStream(new FileOutputStream(newFilePath, true)));
|
||||
|
||||
close();
|
||||
|
||||
bytesWritten = currentFileLength;
|
||||
currentPath = newFilePath;
|
||||
out = newOut;
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
logger.error("Error switch log file", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the file output stream being used for logging.
|
||||
*/
|
||||
private void close() {
|
||||
if (out != null) {
|
||||
out.flush();
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the directory path of the log file.
|
||||
*/
|
||||
protected String makeDirIfRequired(String dir) {
|
||||
|
||||
File f = new File(dir);
|
||||
if (f.exists()) {
|
||||
if (!f.isDirectory()) {
|
||||
String msg = "Transaction logs directory is a file? " + dir;
|
||||
throw new PersistenceException(msg);
|
||||
}
|
||||
} else {
|
||||
if (!f.mkdirs()) {
|
||||
String msg = "Failed to create transaction logs directory " + dir;
|
||||
logger.error(msg);
|
||||
}
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
}
|
||||
-82
@@ -1,82 +0,0 @@
|
||||
package com.avaje.ebeaninternal.server.transaction.log;
|
||||
|
||||
import com.avaje.ebean.config.GlobalProperties;
|
||||
import com.avaje.ebean.config.ServerConfig;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogBuffer;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogWriter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Wraps a FileTransactionLogger to provide delayed initialisation.
|
||||
* <p>
|
||||
* This means that it should only create the log file WHEN there is something
|
||||
* actually logged. This means the logLevel can start at NONE and then change at
|
||||
* runtime (and the log file will then be initialised). NOTE that a volatile
|
||||
* with double checked locking is used to make this transition thread safe.
|
||||
* </p>
|
||||
*
|
||||
* @author rbygrave
|
||||
*
|
||||
*/
|
||||
public class FileTransactionLoggerWrapper implements TransactionLogWriter {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(FileTransactionLoggerWrapper.class);
|
||||
|
||||
private final String serverName;
|
||||
private final String dir;
|
||||
private final int maxFileSize;
|
||||
|
||||
private volatile FileTransactionLogger logWriter;
|
||||
|
||||
public FileTransactionLoggerWrapper(ServerConfig serverConfig) {
|
||||
|
||||
String evalDir = serverConfig.getLoggingDirectoryWithEval();
|
||||
this.dir = evalDir != null ? evalDir : "logs";
|
||||
this.maxFileSize = GlobalProperties.getInt("ebean.logging.maxFileSize", 100 * 1024 * 1024);
|
||||
this.serverName = serverConfig.getName();
|
||||
}
|
||||
|
||||
private FileTransactionLogger initialiseLogger() {
|
||||
|
||||
synchronized (this) {
|
||||
// double check locking here so logWriter NEEDS to be volatile!!
|
||||
FileTransactionLogger writer = this.logWriter;
|
||||
if (writer != null) {
|
||||
return writer;
|
||||
}
|
||||
|
||||
String middleName = GlobalProperties.get("ebean.logging.filename", "_txn_");
|
||||
String logPrefix = serverName + middleName;
|
||||
String threadName = "Ebean-" + serverName + "-TxnLogWriter";
|
||||
|
||||
// create the real logger and start it
|
||||
FileTransactionLogger newLogWriter = new FileTransactionLogger(threadName, dir, logPrefix, maxFileSize);
|
||||
|
||||
// assignment of volatile field
|
||||
this.logWriter = newLogWriter;
|
||||
|
||||
// start background thread for the writer
|
||||
newLogWriter.start();
|
||||
logger.info("Transaction logs in: " + dir);
|
||||
return newLogWriter;
|
||||
}
|
||||
}
|
||||
|
||||
public void log(TransactionLogBuffer logBuffer) {
|
||||
// volatile read
|
||||
FileTransactionLogger writer = this.logWriter;
|
||||
if (writer == null) {
|
||||
writer = initialiseLogger();
|
||||
}
|
||||
writer.log(logBuffer);
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
if (logWriter != null) {
|
||||
logWriter.shutdown();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
package com.avaje.ebeaninternal.server.transaction.log;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.avaje.ebean.config.ServerConfig;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogBuffer;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogBuffer.LogEntry;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogWriter;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* A transactionLogger that uses a java.util.logging.Logger.
|
||||
* <p>
|
||||
* See {@link ServerConfig#setUseJuliTransactionLogger(boolean)}
|
||||
* </p>
|
||||
* @author rbygrave
|
||||
*/
|
||||
public class JuliTransactionLogger implements TransactionLogWriter {
|
||||
private static final Logger logger = Logger.getLogger(JuliTransactionLogger.class.getName());
|
||||
|
||||
public void log(TransactionLogBuffer logBuffer) {
|
||||
|
||||
String txnId = logBuffer.getTransactionId();
|
||||
|
||||
List<LogEntry> messages = logBuffer.messages();
|
||||
for (int i = 0; i < messages.size(); i++) {
|
||||
LogEntry logEntry = messages.get(i);
|
||||
log(txnId, logEntry);
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
}
|
||||
|
||||
private void log(String txnId, LogEntry entry) {
|
||||
|
||||
String message = entry.getMsg();
|
||||
if (txnId != null && message != null && !message.startsWith("Trans[")){
|
||||
message = "Trans["+txnId+"] "+message;
|
||||
}
|
||||
|
||||
logger.info(message);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
package com.avaje.ebeaninternal.server.transaction.log;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
/**
|
||||
* Utility object used to in logging time.
|
||||
* <p>
|
||||
* Used in place of SimpleDateFormat which requires synchronization. Determines
|
||||
* if the day has changed and returns a format of the current time and day.
|
||||
* </p>
|
||||
*/
|
||||
public class LogTime {
|
||||
|
||||
private static final String[] sep = { ":", "." };
|
||||
|
||||
private static LogTime day;
|
||||
static {
|
||||
day = new LogTime();
|
||||
}
|
||||
|
||||
public static LogTime get() {
|
||||
return day;
|
||||
}
|
||||
|
||||
public static LogTime nextDay() {
|
||||
LogTime d = new LogTime();
|
||||
day = d;
|
||||
return d;
|
||||
}
|
||||
|
||||
public static LogTime getWithCheck() {
|
||||
LogTime d = day;
|
||||
if (d.isNextDay()) {
|
||||
return nextDay();
|
||||
} else {
|
||||
return d;
|
||||
}
|
||||
}
|
||||
|
||||
private final String ymd;
|
||||
|
||||
private final long startMidnight;
|
||||
|
||||
private final long startTomorrow;
|
||||
|
||||
/**
|
||||
* Because every variable is private final the constructor should be thread
|
||||
* safe (In JDK5+).
|
||||
*/
|
||||
private LogTime() {
|
||||
|
||||
GregorianCalendar now = new GregorianCalendar();
|
||||
|
||||
now.set(Calendar.HOUR_OF_DAY, 0);
|
||||
now.set(Calendar.MINUTE, 0);
|
||||
now.set(Calendar.SECOND, 0);
|
||||
now.set(Calendar.MILLISECOND, 0);
|
||||
|
||||
this.startMidnight = now.getTime().getTime();
|
||||
this.ymd = getDayDerived(now);
|
||||
|
||||
now.add(Calendar.DATE, 1);
|
||||
this.startTomorrow = now.getTime().getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if we have moved into tomorrow. This is used to trigger log
|
||||
* switching if required.
|
||||
*/
|
||||
public boolean isNextDay() {
|
||||
return (System.currentTimeMillis() >= startTomorrow);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the Year Month Day for today.
|
||||
*/
|
||||
public String getYMD() {
|
||||
return ymd;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current time specify the separators.
|
||||
* <p>
|
||||
* The separators is a String[2] with the first string separating hours
|
||||
* minutes and seconds and the second separating seconds from millis.
|
||||
* </p>
|
||||
* <p>
|
||||
* The default is {":","."}
|
||||
* </p>
|
||||
*/
|
||||
public String getNow(String[] separators) {
|
||||
|
||||
return getTimestamp(System.currentTimeMillis(), separators);
|
||||
|
||||
}
|
||||
|
||||
public String getTimestamp(long systime) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
getTime(sb, systime, startMidnight, sep);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public String getTimestamp(long systime, String[] separators) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
getTime(sb, systime, startMidnight, separators);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current time.
|
||||
* <p>
|
||||
* Format used is hours:minutes:seconds.millis
|
||||
* </p>
|
||||
*/
|
||||
public String getNow() {
|
||||
return getNow(sep);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the derived day information.
|
||||
*/
|
||||
private String getDayDerived(Calendar now) {
|
||||
|
||||
int nowyear = now.get(Calendar.YEAR);
|
||||
int nowmonth = now.get(Calendar.MONTH);
|
||||
int nowday = now.get(Calendar.DAY_OF_MONTH);
|
||||
|
||||
nowmonth++;
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
format(sb, nowyear, 4);
|
||||
format(sb, nowmonth, 2);
|
||||
format(sb, nowday, 2);
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void getTime(StringBuilder sb, long time, long midnight, String[] separator) {
|
||||
|
||||
long rem = time - midnight;// startMidnight;
|
||||
|
||||
long millis = rem % 1000;
|
||||
rem = rem / 1000;
|
||||
long secs = rem % 60;
|
||||
rem = rem / 60;
|
||||
long mins = rem % 60;
|
||||
rem = rem / 60;
|
||||
long hrs = rem;
|
||||
|
||||
format(sb, hrs, 2);
|
||||
sb.append(separator[0]);
|
||||
format(sb, mins, 2);
|
||||
sb.append(separator[0]);
|
||||
format(sb, secs, 2);
|
||||
sb.append(separator[1]);
|
||||
format(sb, millis, 3);
|
||||
}
|
||||
|
||||
private void format(StringBuilder sb, long value, int places) {
|
||||
String format = Long.toString(value);
|
||||
|
||||
int pad = places - format.length();
|
||||
for (int i = 0; i < pad; i++) {
|
||||
sb.append("0");
|
||||
}
|
||||
sb.append(format);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,304 +0,0 @@
|
||||
package com.avaje.ebeaninternal.server.transaction.log;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.PrintStream;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
|
||||
/**
|
||||
* File based logger that can switch daily. It will include the date in the
|
||||
* files name.
|
||||
* <p>
|
||||
* Administration Note: If log file switching fails it will send the error to
|
||||
* standard out and standard err print streams. This is assumed to be rather
|
||||
* unlikely but possible.
|
||||
* </p>
|
||||
*/
|
||||
public class SimpleLogger {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SimpleLogger.class);
|
||||
|
||||
/**
|
||||
* Used to print stack trace.
|
||||
*/
|
||||
private static final String atString = " at ";
|
||||
|
||||
/**
|
||||
* The output stream.
|
||||
*/
|
||||
private PrintStream out;
|
||||
|
||||
/**
|
||||
* Whether to append or replace.
|
||||
*/
|
||||
private boolean doAppend = true;
|
||||
|
||||
/**
|
||||
* Flag to indicate the logger if the logger has been closed.
|
||||
*/
|
||||
private boolean open = true;
|
||||
|
||||
/**
|
||||
* The current file path.
|
||||
*/
|
||||
private String currentPath;
|
||||
|
||||
/**
|
||||
* The path of the log file.
|
||||
*/
|
||||
private final String filepath;
|
||||
|
||||
/**
|
||||
* Set to true if using daily file switching.
|
||||
*/
|
||||
private final boolean useFileSwitching;
|
||||
|
||||
/**
|
||||
* The maximum number of stack lines to output.
|
||||
* This is just for transaction logging so 5 is fine.
|
||||
*/
|
||||
private final int maxStackTraceLines = 5;
|
||||
|
||||
/**
|
||||
* The delimiter to use.
|
||||
*/
|
||||
private final String deliminator;
|
||||
|
||||
/**
|
||||
* Object used to synch the file switching.
|
||||
*/
|
||||
private final Object fileMonitor = new Object();
|
||||
|
||||
/**
|
||||
* The prefix of the log file name.
|
||||
*/
|
||||
private final String logFileName;
|
||||
|
||||
/**
|
||||
* The file suffix for the logs.
|
||||
*/
|
||||
private final String logFileSuffix;
|
||||
|
||||
/**
|
||||
* The newLineChar used instead of NL or CRNL.
|
||||
*/
|
||||
private final String newLineChar = "\\r\\n";
|
||||
|
||||
private final boolean csv;
|
||||
|
||||
/**
|
||||
* Create a logger with a logFileName and useFileSwitching flag.
|
||||
*
|
||||
* @param dir
|
||||
* the sub directory to put the log. Can be null.
|
||||
* @param logFileName
|
||||
* the prefix log file name.
|
||||
* @param useFileSwitching
|
||||
* if true then use daily file switching.
|
||||
*/
|
||||
public SimpleLogger(String dir, String logFileName, boolean useFileSwitching, String suffix) {
|
||||
this.logFileName = logFileName;
|
||||
this.useFileSwitching = useFileSwitching;
|
||||
this.logFileSuffix = "."+suffix;
|
||||
csv = "csv".equalsIgnoreCase(suffix);
|
||||
deliminator = csv ? "," : ", ";
|
||||
try {
|
||||
|
||||
// get the directory where the log files are going to go
|
||||
filepath = makeDirIfRequired(dir);
|
||||
|
||||
switchFile(LogTime.nextDay());
|
||||
|
||||
} catch (Exception e) {
|
||||
// Not going to use logger to show logger exceptions...
|
||||
// Using standard out and standard err instead.
|
||||
System.out.println("FATAL ERROR: init of FileLogger: " + e.getMessage());
|
||||
System.err.println("FATAL ERROR: init of FileLogger: " + e.getMessage());
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public SimpleLogger(String dir, String logFileName, boolean useFileSwitching) {
|
||||
this(dir, logFileName, useFileSwitching, "log");
|
||||
}
|
||||
|
||||
protected void finalize() throws Throwable {
|
||||
close();
|
||||
super.finalize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the file output stream being used for logging.
|
||||
*/
|
||||
public void close() {
|
||||
if (open) {
|
||||
out.flush();
|
||||
out.close();
|
||||
open = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void log(String msg) {
|
||||
log(null, msg, null);
|
||||
}
|
||||
|
||||
public void log(String msg, Throwable e) {
|
||||
log(null, msg, e);
|
||||
}
|
||||
|
||||
/**
|
||||
* Log the event to the file.
|
||||
*/
|
||||
public void log(String transId, String msg, Throwable e) {
|
||||
|
||||
// check to see if we need to switch file?
|
||||
LogTime logTime = LogTime.get();
|
||||
if (logTime.isNextDay()) {
|
||||
logTime = LogTime.nextDay();
|
||||
try {
|
||||
switchFile(logTime);
|
||||
} catch (Exception ex) {
|
||||
// This is a pretty serious error... not logging it though as
|
||||
// this could be recursive so just going to send to std err
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// prefix of transID and timestamp ~ 40 chars
|
||||
int roughSize = 40;
|
||||
if (msg != null) {
|
||||
roughSize += msg.length();
|
||||
}
|
||||
if (e != null) {
|
||||
roughSize += 200;
|
||||
}
|
||||
|
||||
StringBuilder line = new StringBuilder(roughSize);
|
||||
if (transId != null){
|
||||
line.append("trans[").append(transId).append("]").append(deliminator);
|
||||
}
|
||||
|
||||
if (csv){
|
||||
line.append("\"'");
|
||||
}
|
||||
line.append(logTime.getNow());
|
||||
if (csv){
|
||||
line.append("'\"");
|
||||
}
|
||||
line.append(deliminator);
|
||||
|
||||
if (msg != null) {
|
||||
line.append(msg).append(" ");
|
||||
}
|
||||
|
||||
printThrowable(line, e, false);
|
||||
|
||||
String lineString = line.toString();
|
||||
|
||||
synchronized (fileMonitor) {
|
||||
out.println(lineString);
|
||||
// without flush automatic close() *MUST* be called
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively output the Throwable stack trace to the log.
|
||||
*
|
||||
* @param sb
|
||||
* the buffer to write the stack trace to
|
||||
* @param e
|
||||
* the source throwable
|
||||
* @param isCause
|
||||
* flag to indicate if this is the top level throwable or a cause
|
||||
*/
|
||||
protected void printThrowable(StringBuilder sb, Throwable e, boolean isCause) {
|
||||
if (e != null) {
|
||||
if (isCause) {
|
||||
sb.append("Caused by: ");
|
||||
}
|
||||
sb.append(e.getClass().getName());
|
||||
sb.append(":");
|
||||
sb.append(e.getMessage()).append(newLineChar);
|
||||
|
||||
StackTraceElement[] ste = e.getStackTrace();
|
||||
int outputStackLines = ste.length;
|
||||
int notShownCount = 0;
|
||||
if (ste.length > maxStackTraceLines) {
|
||||
outputStackLines = maxStackTraceLines;
|
||||
notShownCount = ste.length - outputStackLines;
|
||||
}
|
||||
for (int i = 0; i < outputStackLines; i++) {
|
||||
sb.append(atString);
|
||||
sb.append(ste[i].toString()).append(newLineChar);
|
||||
}
|
||||
if (notShownCount > 0) {
|
||||
sb.append(" ... ");
|
||||
sb.append(notShownCount);
|
||||
sb.append(" more").append(newLineChar);
|
||||
}
|
||||
Throwable cause = e.getCause();
|
||||
if (cause != null) {
|
||||
printThrowable(sb, cause, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new file and sets the file logging output to be directed to the
|
||||
* new file.
|
||||
*
|
||||
* @exception Exception
|
||||
* indicates a problem writing to the new log file.
|
||||
*/
|
||||
protected void switchFile(LogTime logTime) throws Exception {
|
||||
|
||||
String newFilePath = filepath + File.separator + logFileName;
|
||||
|
||||
if (useFileSwitching) {
|
||||
// For file switching include the date in the file name
|
||||
newFilePath = newFilePath + logTime.getYMD() + logFileSuffix;
|
||||
|
||||
} else {
|
||||
newFilePath = newFilePath + logFileSuffix;
|
||||
}
|
||||
|
||||
// Try to open an output stream to the file
|
||||
synchronized (fileMonitor) {
|
||||
|
||||
if (!newFilePath.equals(currentPath)) {
|
||||
currentPath = newFilePath;
|
||||
|
||||
out = new PrintStream(new BufferedOutputStream(new FileOutputStream(newFilePath,
|
||||
doAppend)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the directory path of the log file.
|
||||
*/
|
||||
protected String makeDirIfRequired(String dir) {
|
||||
|
||||
File f = new File(dir);
|
||||
if (f.exists()){
|
||||
if (!f.isDirectory()){
|
||||
String msg = "Transaction logs directory is a file? "+dir;
|
||||
throw new PersistenceException(msg);
|
||||
}
|
||||
} else {
|
||||
if (!f.mkdirs()) {
|
||||
String msg = "Failed to create transaction logs directory "+dir;
|
||||
logger.error(msg);
|
||||
}
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=iso-8859-1">
|
||||
<TITLE>Transaction Logging</TITLE>
|
||||
</HEAD>
|
||||
<Body BGCOLOR="#ffffff">
|
||||
Transaction logging
|
||||
|
||||
</Body>
|
||||
</HTML>
|
||||
Reference in new issue
Block a user