Skip to content

Instantly share code, notes, and snippets.

@eeichinger
Created November 26, 2012 16:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eeichinger/4149191 to your computer and use it in GitHub Desktop.
Save eeichinger/4149191 to your computer and use it in GitHub Desktop.
A logback SocketHubAppender implementation - shamelessly stolen from log4j and adapted to logback. Just copy & paste into your project
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package logback;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.LineNumberReader;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Vector;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.ThrowableProxy;
import ch.qos.logback.core.AppenderBase;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.helpers.CyclicBuffer;
/**
Sends {@link ILoggingEvent} objects to a set of remote log servers,
usually a {@link org.apache.log4j.net.SocketNode SocketNodes}.
<p>Acts just like {@link org.apache.log4j.net.SocketAppender} except that instead of
connecting to a given remote log server,
<code>SocketHubAppender</code> accepts connections from the remote
log servers as clients. It can accept more than one connection.
When a log event is received, the event is sent to the set of
currently connected remote log servers. Implemented this way it does
not require any update to the configuration file to send data to
another remote log server. The remote log server simply connects to
the host and port the <code>SocketHubAppender</code> is running on.
<p>The <code>SocketHubAppender</code> does not store events such
that the remote side will events that arrived after the
establishment of its connection. Once connected, events arrive in
order as guaranteed by the TCP protocol.
<p>This implementation borrows heavily from the {@link
org.apache.log4j.net.SocketAppender}.
<p>The SocketHubAppender has the following characteristics:
<ul>
<p><li>If sent to a {@link org.apache.log4j.net.SocketNode}, logging is non-intrusive as
far as the log event is concerned. In other words, the event will be
logged with the same time stamp, {@link org.apache.log4j.NDC},
location info as if it were logged locally.
<p><li><code>SocketHubAppender</code> does not use a layout. It
ships a serialized {@link ILoggingEvent} object to the remote side.
<p><li><code>SocketHubAppender</code> relies on the TCP
protocol. Consequently, if the remote side is reachable, then log
events will eventually arrive at remote client.
<p><li>If no remote clients are attached, the logging requests are
simply dropped.
<p><li>Logging events are automatically <em>buffered</em> by the
native TCP implementation. This means that if the link to remote
client is slow but still faster than the rate of (log) event
production, the application will not be affected by the slow network
connection. However, if the network connection is slower then the
rate of event production, then the local application can only
progress at the network rate. In particular, if the network link to
the the remote client is down, the application will be blocked.
<p>On the other hand, if the network link is up, but the remote
client is down, the client will not be blocked when making log
requests but the log events will be lost due to client
unavailability.
<p>The single remote client case extends to multiple clients
connections. The rate of logging will be determined by the slowest
link.
<p><li>If the JVM hosting the <code>SocketHubAppender</code> exits
before the <code>SocketHubAppender</code> is closed either
explicitly or subsequent to garbage collection, then there might
be untransmitted data in the pipe which might be lost. This is a
common problem on Windows based systems.
<p>To avoid lost data, it is usually sufficient to {@link #stop}
the <code>SocketHubAppender</code> either explicitly or by calling
the {@link org.apache.log4j.LogManager#shutdown} method before
exiting the application.
</ul>
@author Mark Womack */
public class LogbackSocketHubAppender<E extends ch.qos.logback.classic.spi.LoggingEvent> extends AppenderBase<E>
{
/**
* It is the encoder which is ultimately responsible for writing the event to
* an {@link java.io.OutputStream}.
*/
private Layout<E> layout;
public void setLayout(Layout<E> layout) {
this.layout = layout;
}
/**
The default port number of the ServerSocket will be created on. */
static final int DEFAULT_PORT = 4560;
private int port = DEFAULT_PORT;
private Vector<ObjectOutputStream> oosList = new Vector<ObjectOutputStream>();
private ServerMonitor serverMonitor = null;
private boolean locationInfo = false;
private CyclicBuffer<LoggingEvent> buffer = null;
private String application;
private boolean advertiseViaMulticastDNS;
// private ZeroConfSupport zeroConf;
// private Layout layout;
private class LogLogAdapter {
void debug(String msg) {
addInfo( msg );
}
void error(String msg) {
addError( msg );
}
void error(String msg, Throwable t) {
addError(msg, t);
}
}
private LogLogAdapter LogLog = new LogLogAdapter();
/**
* The MulticastDNS zone advertised by a SocketHubAppender
*/
public static final String ZONE = "_log4j_obj_tcpaccept_appender.local.";
private ServerSocket serverSocket;
public LogbackSocketHubAppender() { }
/**
Connects to remote server at <code>address</code> and <code>port</code>. */
public LogbackSocketHubAppender( int _port ) {
port = _port;
startServer();
}
/**
Set up the socket server on the specified port. */
synchronized
public
void start() {
// if (advertiseViaMulticastDNS) {
// zeroConf = new ZeroConfSupport(ZONE, port, getName());
// zeroConf.advertise();
// }
// if (this.layout == null) {
// addError("No layout set for the appender named [" + name + "].");
// return;
// }
startServer();
super.start();
}
/**
Close this appender.
<p>This will mark the appender as closed and
call then {@link #cleanUp} method. */
synchronized
public
void stop() {
if(!started)
return;
LogLog.debug("closing SocketHubAppender " + getName());
// this.closed = true;
// if (advertiseViaMulticastDNS) {
// zeroConf.unadvertise();
// }
cleanUp();
LogLog.debug("SocketHubAppender " + getName() + " closed");
super.stop();
}
/**
Release the underlying ServerMonitor thread, and drop the connections
to all connected remote servers. */
public
void cleanUp() {
// stop the monitor thread
LogLog.debug("stopping ServerSocket");
serverMonitor.stopMonitor();
serverMonitor = null;
// close all of the connections
LogLog.debug("closing client connections");
while (oosList.size() != 0) {
ObjectOutputStream oos = oosList.elementAt(0);
if(oos != null) {
try {
oos.close();
} catch(InterruptedIOException e) {
Thread.currentThread().interrupt();
LogLog.error("could not close oos.", e);
} catch(IOException e) {
LogLog.error("could not close oos.", e);
}
oosList.removeElementAt(0);
}
}
}
/**
Append an event to all of current connections. */
public
void append(E ev) {
if (ev == null) {
return;
}
if (locationInfo) {
ev.getCallerData();
}
LoggingEvent event = new LoggingEvent(ev);
if (buffer != null) {
buffer.add(event);
}
// if no open connections, exit now
if (oosList.size() == 0) {
return;
}
// loop through the current set of open connections, appending the event to each
for (int streamCount = 0; streamCount < oosList.size(); streamCount++) {
ObjectOutputStream oos = null;
try {
oos = oosList.elementAt(streamCount);
}
catch (ArrayIndexOutOfBoundsException e) {
// catch this, but just don't assign a value
// this should not really occur as this method is
// the only one that can remove oos's (besides cleanUp).
}
// list size changed unexpectedly? Just exit the append.
if (oos == null)
break;
try {
oos.writeObject( event );
oos.flush();
// Failing to reset the object output stream every now and
// then creates a serious memory leak.
// right now we always reset. TODO - set up frequency counter per oos?
oos.reset();
}
catch(IOException e) {
if (e instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
// there was an io exception so just drop the connection
oosList.removeElementAt(streamCount);
LogLog.debug("dropped connection");
// decrement to keep the counter in place (for loop always increments)
streamCount--;
}
}
}
/**
The SocketHubAppender does not use a layout. Hence, this method returns
<code>false</code>. */
public
boolean requiresLayout() {
return false;
}
/**
The <b>Port</b> option takes a positive integer representing
the port where the server is waiting for connections. */
public
void setPort(int _port) {
port = _port;
}
/**
* The <b>App</b> option takes a string value which should be the name of the application getting logged. If property was already set (via system
* property), don't set here.
*/
public
void setApplication(String lapp) {
this.application = lapp;
}
/**
* Returns value of the <b>Application</b> option.
*/
public
String getApplication() {
return application;
}
/**
Returns value of the <b>Port</b> option. */
public
int getPort() {
return port;
}
/**
* The <b>BufferSize</b> option takes a positive integer representing the number of events this appender will buffer and send to newly connected
* clients.
*/
public
void setBufferSize(int _bufferSize) {
buffer = new CyclicBuffer(_bufferSize);
}
/**
* Returns value of the <b>bufferSize</b> option.
*/
public
int getBufferSize() {
if (buffer == null) {
return 0;
} else {
return buffer.getMaxSize();
}
}
/**
The <b>LocationInfo</b> option takes a boolean value. If true,
the information sent to the remote host will include location
information. By default no location information is sent to the server. */
public
void setLocationInfo(boolean _locationInfo) {
locationInfo = _locationInfo;
}
/**
Returns value of the <b>LocationInfo</b> option. */
public
boolean getLocationInfo() {
return locationInfo;
}
public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) {
this.advertiseViaMulticastDNS = advertiseViaMulticastDNS;
}
public boolean isAdvertiseViaMulticastDNS() {
return advertiseViaMulticastDNS;
}
/**
Start the ServerMonitor thread. */
private
void startServer() {
serverMonitor = new ServerMonitor(port, oosList);
}
/**
* Creates a server socket to accept connections.
* @param socketPort port on which the socket should listen, may be zero.
* @return new socket.
* @throws IOException IO error when opening the socket.
*/
protected ServerSocket createServerSocket(final int socketPort) throws IOException {
return new ServerSocket(socketPort);
}
/**
This class is used internally to monitor a ServerSocket
and register new connections in a vector passed in the
constructor. */
private class ServerMonitor implements Runnable {
private int port;
private Vector<ObjectOutputStream> oosList;
private boolean keepRunning;
private Thread monitorThread;
/**
Create a thread and start the monitor. */
public
ServerMonitor(int _port, Vector<ObjectOutputStream> _oosList) {
port = _port;
oosList = _oosList;
keepRunning = true;
monitorThread = new Thread(this);
monitorThread.setDaemon(true);
monitorThread.setName("SocketHubAppender-Monitor-" + port);
monitorThread.start();
}
/**
Stops the monitor. This method will not return until
the thread has finished executing. */
public synchronized void stopMonitor() {
if (keepRunning) {
LogLog.debug("server monitor thread shutting down");
keepRunning = false;
try {
if (serverSocket != null) {
serverSocket.close();
serverSocket = null;
}
} catch (IOException ioe) {}
try {
monitorThread.join();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
// do nothing?
}
// release the thread
monitorThread = null;
LogLog.debug("server monitor thread shut down");
}
}
private
void sendCachedEvents(ObjectOutputStream stream) throws IOException {
if (buffer != null) {
for (int i = 0; i < buffer.length(); i++) {
stream.writeObject( buffer.get( i ) );
}
stream.flush();
stream.reset();
}
}
/**
Method that runs, monitoring the ServerSocket and adding connections as
they connect to the socket. */
public
void run() {
serverSocket = null;
try {
serverSocket = createServerSocket(port);
serverSocket.setSoTimeout(1000);
}
catch (Exception e) {
if (e instanceof InterruptedIOException || e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
LogLog.error("exception setting timeout, shutting down server socket.", e);
keepRunning = false;
return;
}
try {
try {
serverSocket.setSoTimeout(1000);
}
catch (SocketException e) {
LogLog.error("exception setting timeout, shutting down server socket.", e);
return;
}
while (keepRunning) {
Socket socket = null;
try {
socket = serverSocket.accept();
}
catch (InterruptedIOException e) {
// timeout occurred, so just loop
}
catch (SocketException e) {
LogLog.error("exception accepting socket, shutting down server socket.", e);
keepRunning = false;
}
catch (IOException e) {
LogLog.error("exception accepting socket.", e);
}
// if there was a socket accepted
if (socket != null) {
try {
InetAddress remoteAddress = socket.getInetAddress();
LogLog.debug("accepting connection from " + remoteAddress.getHostName()
+ " (" + remoteAddress.getHostAddress() + ")");
// create an ObjectOutputStream
ObjectOutputStream oos = new ClassNameRewritingObjectOutputStream(socket.getOutputStream());
if (buffer != null && buffer.length() > 0) {
sendCachedEvents(oos);
}
// add it to the oosList. OK since Vector is synchronized.
oosList.addElement(oos);
} catch (IOException e) {
if (e instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
LogLog.error("exception creating output stream on socket.", e);
}
}
}
}
finally {
// close the socket
try {
serverSocket.close();
} catch(InterruptedIOException e) {
Thread.currentThread().interrupt();
} catch (IOException e) {
// do nothing with it?
}
}
}
}
private static class ClassNameRewritingObjectOutputStream extends ObjectOutputStream
{
public ClassNameRewritingObjectOutputStream( OutputStream out ) throws IOException
{
super( out );
}
boolean rewriteClassname = false;
@Override protected void writeClassDescriptor( ObjectStreamClass desc ) throws IOException
{
rewriteClassname = true;
super.writeClassDescriptor( desc );
}
@Override public void writeUTF( String str ) throws IOException
{
if (rewriteClassname) str = str.replace("logback.","org.apache.log4j.spi.");
rewriteClassname = false;
super.writeUTF( str );
}
}
}
class LocationInfo implements java.io.Serializable {
static final long serialVersionUID = -1325822038990805636L;
public String fullInfo;
public LocationInfo( StackTraceElement[] stack )
{
// this.fullInfo = stack[0].getFileName() + ":" + stack[0].getLineNumber();
this(stack[0].getFileName(), stack[0].getClassName(), stack[0].getMethodName(), stack[0].getLineNumber());
}
public LocationInfo(
final String file,
final String classname,
final String method,
final int line) {
// String fileName = file;
// String className = classname;
// String methodName = method;
// String lineNumber = line;
StringBuffer buf = new StringBuffer();
appendFragment(buf, classname);
buf.append(".");
appendFragment(buf, method);
buf.append("(");
appendFragment(buf, file);
buf.append(":");
appendFragment(buf, ""+line);
buf.append(")");
this.fullInfo = buf.toString();
}
private static final void appendFragment(final StringBuffer buf,
final String fragment) {
if (fragment == null) {
buf.append("?");
} else {
buf.append(fragment);
}
}
}
class ThrowableInformation implements java.io.Serializable {
static final long serialVersionUID = -4748765566864322735L;
private String[] rep;
public
ThrowableInformation(Throwable throwable) {
this.rep = render(throwable);
}
public
ThrowableInformation(IThrowableProxy throwable) {
this.rep = render( ((ThrowableProxy)throwable).getThrowable() );
}
public static String[] render(final Throwable throwable) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
throwable.printStackTrace(pw);
} catch(RuntimeException ex) {
}
pw.flush();
LineNumberReader reader = new LineNumberReader(
new StringReader(sw.toString()));
ArrayList lines = new ArrayList();
try {
String line = reader.readLine();
while(line != null) {
lines.add(line);
line = reader.readLine();
}
} catch(IOException ex) {
if (ex instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
lines.add(ex.toString());
}
String[] tempRep = new String[lines.size()];
lines.toArray(tempRep);
return tempRep;
}
}
class LoggingEvent implements java.io.Serializable {
private static long startTime = System.currentTimeMillis();
// /** Fully qualified name of the calling category class. */
// transient public final String fqnOfCategoryClass;
// /**
// * The category of the logging event. This field is not serialized
// * for performance reasons.
// *
// * <p>It is set by the LoggingEvent constructor or set by a remote
// * entity after deserialization.
// *
// * @deprecated This field will be marked as private or be completely
// * removed in future releases. Please do not use it.
// * */
// transient private Category logger;
/**
* <p>The category (logger) name.
*
* @deprecated This field will be marked as private in future
* releases. Please do not access it directly. Use the {@link
* #getLoggerName} method instead.
* */
final public String categoryName;
// /**
// * Level of logging event. Level cannot be serializable because it
// * is a flyweight. Due to its special seralization it cannot be
// * declared final either.
// *
// * <p> This field should not be accessed directly. You shoud use the
// * {@link #getLevel} method instead.
// *
// * @deprecated This field will be marked as private in future
// * releases. Please do not access it directly. Use the {@link
// * #getLevel} method instead.
// * */
transient public Level level;
/** The nested diagnostic context (NDC) of logging event. */
private String ndc;
/** The mapped diagnostic context (MDC) of logging event. */
private Hashtable mdcCopy;
/** Have we tried to do an NDC lookup? If we did, there is no need
* to do it again. Note that its value is always false when
* serialized. Thus, a receiving SocketNode will never use it's own
* (incorrect) NDC. See also writeObject method. */
private boolean ndcLookupRequired = true;
/** Have we tried to do an MDC lookup? If we did, there is no need
* to do it again. Note that its value is always false when
* serialized. See also the getMDC and getMDCCopy methods. */
private boolean mdcCopyLookupRequired = true;
// /** The application supplied message of logging event. */
// transient private Object message;
/** The application supplied message rendered through the log4j
objet rendering mechanism.*/
private String renderedMessage;
/** The name of thread in which this logging event was generated. */
private String threadName;
/** This
variable contains information about this event's throwable
*/
private ThrowableInformation throwableInfo;
/** The number of milliseconds elapsed from 1/1/1970 until logging event
was created. */
public final long timeStamp;
/** Location information for the caller. */
private LocationInfo locationInfo;
// Serialization
static final long serialVersionUID = -868428216207166145L;
public LoggingEvent(String categoryName, Level level, ThrowableInformation throwableInfo) {
this.categoryName = categoryName;
this.level = level;
this.throwableInfo = throwableInfo;
this.timeStamp = System.currentTimeMillis();
}
public LoggingEvent(ch.qos.logback.classic.spi.LoggingEvent ev) {
this.categoryName = ev.getLoggerName();
this.level = ev.getLevel();
this.threadName = ev.getThreadName();
this.renderedMessage = ev.getFormattedMessage();
this.mdcCopy = new Hashtable(ev.getMDCPropertyMap());
this.throwableInfo = new ThrowableInformation(ev.getThrowableProxy());
this.timeStamp = ev.getTimeStamp();
this.ndc = ev.getLoggerContextVO().getName();
if (ev.hasCallerData()) {
this.locationInfo = new LocationInfo(ev.getCallerData());
}
}
// /**
// Instantiate a LoggingEvent from the supplied parameters.
//
// <p>Except {@link #timeStamp} all the other fields of
// <code>LoggingEvent</code> are filled when actually needed.
// <p>
// @param logger The logger generating this event.
// @param level The level of this event.
// @param message The message of this event.
// @param throwable The throwable of this event. */
// public LoggingEvent(String fqnOfCategoryClass, Category logger,
// Priority level, Object message, Throwable throwable) {
// this.fqnOfCategoryClass = fqnOfCategoryClass;
// this.logger = logger;
// this.categoryName = logger.getName();
// this.level = level;
// this.message = message;
// if(throwable != null) {
// this.throwableInfo = new ThrowableInformation(throwable, logger);
// }
// timeStamp = System.currentTimeMillis();
// }
// /**
// Instantiate a LoggingEvent from the supplied parameters.
//
// <p>Except {@link #timeStamp} all the other fields of
// <code>LoggingEvent</code> are filled when actually needed.
// <p>
// @param logger The logger generating this event.
// @param timeStamp the timestamp of this logging event
// @param level The level of this event.
// @param message The message of this event.
// @param throwable The throwable of this event. */
// public LoggingEvent(String fqnOfCategoryClass, Category logger,
// long timeStamp, Priority level, Object message,
// Throwable throwable) {
// this.fqnOfCategoryClass = fqnOfCategoryClass;
// this.logger = logger;
// this.categoryName = logger.getName();
// this.level = level;
// this.message = message;
// if(throwable != null) {
// this.throwableInfo = new ThrowableInformation(throwable, logger);
// }
//
// this.timeStamp = timeStamp;
// }
// /**
// Create new instance.
// @since 1.2.15
// @param fqnOfCategoryClass Fully qualified class name
// of Logger implementation.
// @param logger The logger generating this event.
// @param timeStamp the timestamp of this logging event
// @param level The level of this event.
// @param message The message of this event.
// @param threadName thread name
// @param throwable The throwable of this event.
// @param ndc Nested diagnostic context
// @param info Location info
// @param properties MDC properties
// */
// public LoggingEvent(final String fqnOfCategoryClass,
// final Category logger,
// final long timeStamp,
// final Level level,
// final Object message,
// final String threadName,
// final ThrowableInformation throwable,
// final String ndc,
// final LocationInfo info,
// final java.util.Map properties) {
// super();
// this.fqnOfCategoryClass = fqnOfCategoryClass;
// this.logger = logger;
// if (logger != null) {
// categoryName = logger.getName();
// } else {
// categoryName = null;
// }
// this.level = level;
// this.message = message;
// if(throwable != null) {
// this.throwableInfo = throwable;
// }
//
// this.timeStamp = timeStamp;
// this.threadName = threadName;
// ndcLookupRequired = false;
// this.ndc = ndc;
// this.locationInfo = info;
// mdcCopyLookupRequired = false;
// if (properties != null) {
// mdcCopy = new java.util.Hashtable(properties);
// }
// }
// /**
// Set the location information for this logging event. The collected
// information is cached for future use.
// */
// public LocationInfo getLocationInformation() {
// if(locationInfo == null) {
// locationInfo = new LocationInfo(new Throwable(), fqnOfCategoryClass);
// }
// return locationInfo;
// }
// /**
// * Return the level of this event. Use this form instead of directly
// * accessing the <code>level</code> field. */
// public Level getLevel() {
// return (Level) level;
// }
/**
* Return the name of the logger. Use this form instead of directly
* accessing the <code>categoryName</code> field.
*/
public String getLoggerName() {
return categoryName;
}
// /**
// * Gets the logger of the event.
// * Use should be restricted to cloning events.
// * @since 1.2.15
// */
// public Category getLogger() {
// return logger;
// }
// /**
// Return the message for this logging event.
//
// <p>Before serialization, the returned object is the message
// passed by the user to generate the logging event. After
// serialization, the returned value equals the String form of the
// message possibly after object rendering.
//
// @since 1.1 */
// public
// Object getMessage() {
// if(message != null) {
// return message;
// } else {
// return getRenderedMessage();
// }
// }
// /**
// * This method returns the NDC for this event. It will return the
// * correct content even if the event was generated in a different
// * thread or even on a different machine. The {@link NDC#get} method
// * should <em>never</em> be called directly. */
// public
// String getNDC() {
// if(ndcLookupRequired) {
// ndcLookupRequired = false;
// ndc = NDC.get();
// }
// return ndc;
// }
// /**
// Returns the the context corresponding to the <code>key</code>
// parameter. If there is a local MDC copy, possibly because we are
// in a logging server or running inside AsyncAppender, then we
// search for the key in MDC copy, if a value is found it is
// returned. Otherwise, if the search in MDC copy returns a null
// result, then the current thread's <code>MDC</code> is used.
//
// <p>Note that <em>both</em> the local MDC copy and the current
// thread's MDC are searched.
//
// */
// public
// Object getMDC(String key) {
// Object r;
// // Note the mdcCopy is used if it exists. Otherwise we use the MDC
// // that is associated with the thread.
// if(mdcCopy != null) {
// r = mdcCopy.get(key);
// if(r != null) {
// return r;
// }
// }
// return MDC.get(key);
// }
// /**
// Obtain a copy of this thread's MDC prior to serialization or
// asynchronous logging.
// */
// public
// void getMDCCopy() {
// if(mdcCopyLookupRequired) {
// mdcCopyLookupRequired = false;
// // the clone call is required for asynchronous logging.
// // See also bug #5932.
// Hashtable t = (Hashtable) MDC.getContext();
// if(t != null) {
// mdcCopy = (Hashtable) t.clone();
// }
// }
// }
// public
// String getRenderedMessage() {
// if(renderedMessage == null && message != null) {
// if(message instanceof String)
// renderedMessage = (String) message;
// else {
// LoggerRepository repository = logger.getLoggerRepository();
//
// if(repository instanceof RendererSupport) {
// RendererSupport rs = (RendererSupport) repository;
// renderedMessage= rs.getRendererMap().findAndRender(message);
// } else {
// renderedMessage = message.toString();
// }
// }
// }
// return renderedMessage;
// }
/**
Returns the time when the application started, in milliseconds
elapsed since 01.01.1970. */
public static long getStartTime() {
return startTime;
}
public
String getThreadName() {
if(threadName == null)
threadName = (Thread.currentThread()).getName();
return threadName;
}
/**
Returns the throwable information contained within this
event. May be <code>null</code> if there is no such information.
<p>Note that the {@link Throwable} object contained within a
{@link ThrowableInformation} does not survive serialization.
@since 1.1 */
public
ThrowableInformation getThrowableInformation() {
return throwableInfo;
}
// /**
// Return this event's throwable's string[] representaion.
// */
// public
// String[] getThrowableStrRep() {
//
// if(throwableInfo == null)
// return null;
// else
// return throwableInfo.getThrowableStrRep();
// }
// private
// void readLevel(ObjectInputStream ois)
// throws java.io.IOException, ClassNotFoundException {
//
// int p = ois.readInt();
// try {
// String className = (String) ois.readObject();
// if(className == null) {
// level = Level.toLevel(p);
// } else {
// Method m = (Method) methodCache.get(className);
// if(m == null) {
// Class clazz = Loader.loadClass(className);
// // Note that we use Class.getDeclaredMethod instead of
// // Class.getMethod. This assumes that the Level subclass
// // implements the toLevel(int) method which is a
// // requirement. Actually, it does not make sense for Level
// // subclasses NOT to implement this method. Also note that
// // only Level can be subclassed and not Priority.
// m = clazz.getDeclaredMethod(TO_LEVEL, TO_LEVEL_PARAMS);
// methodCache.put(className, m);
// }
// PARAM_ARRAY[0] = new Integer(p);
// level = (Level) m.invoke(null, PARAM_ARRAY);
// }
// } catch(InvocationTargetException e) {
// if (e.getTargetException() instanceof InterruptedException
// || e.getTargetException() instanceof InterruptedIOException) {
// Thread.currentThread().interrupt();
// }
// LogLog.warn("Level deserialization failed, reverting to default.", e);
// level = Level.toLevel(p);
// } catch(NoSuchMethodException e) {
// LogLog.warn("Level deserialization failed, reverting to default.", e);
// level = Level.toLevel(p);
// } catch(IllegalAccessException e) {
// LogLog.warn("Level deserialization failed, reverting to default.", e);
// level = Level.toLevel(p);
// } catch(RuntimeException e) {
// LogLog.warn("Level deserialization failed, reverting to default.", e);
// level = Level.toLevel(p);
// }
// }
// private void readObject(ObjectInputStream ois)
// throws java.io.IOException, ClassNotFoundException {
// ois.defaultReadObject();
// readLevel(ois);
//
// // Make sure that no location info is available to Layouts
// if(locationInfo == null)
// locationInfo = new LocationInfo(null, null);
// }
private
void writeObject(ObjectOutputStream oos) throws java.io.IOException {
// // Aside from returning the current thread name the wgetThreadName
// // method sets the threadName variable.
// this.getThreadName();
//
// // This sets the renders the message in case it wasn't up to now.
// this.getRenderedMessage();
//
// // This call has a side effect of setting this.ndc and
// // setting ndcLookupRequired to false if not already false.
// this.getNDC();
//
// // This call has a side effect of setting this.mdcCopy and
// // setting mdcLookupRequired to false if not already false.
// this.getMDCCopy();
//
// // This sets the throwable sting representation of the event throwable.
// this.getThrowableStrRep();
oos.defaultWriteObject();
// serialize this event's level
writeLevel(oos);
}
private
void writeLevel(ObjectOutputStream oos) throws java.io.IOException {
oos.writeInt(level.toInt()); // TODO
oos.writeObject(null);
// Class clazz = level.getClass();
// if(clazz == Level.class) {
// oos.writeObject(null);
// } else {
// // writing directly the Class object would be nicer, except that
// // serialized a Class object can not be read back by JDK
// // 1.1.x. We have to resort to this hack instead.
// oos.writeObject(clazz.getName());
// }
}
// /**
// * Set value for MDC property.
// * This adds the specified MDC property to the event.
// * Access to the MDC is not synchronized, so this
// * method should only be called when it is known that
// * no other threads are accessing the MDC.
// * @since 1.2.15
// * @param propName
// * @param propValue
// */
// public final void setProperty(final String propName,
// final String propValue) {
// if (mdcCopy == null) {
// getMDCCopy();
// }
// if (mdcCopy == null) {
// mdcCopy = new Hashtable();
// }
// mdcCopy.put(propName, propValue);
// }
// /**
// * Return a property for this event. The return value can be null.
// *
// * Equivalent to getMDC(String) in log4j 1.2. Provided
// * for compatibility with log4j 1.3.
// *
// * @param key property name
// * @return property value or null if property not set
// * @since 1.2.15
// */
// public final String getProperty(final String key) {
// Object value = getMDC(key);
// String retval = null;
// if (value != null) {
// retval = value.toString();
// }
// return retval;
// }
// /**
// * Check for the existence of location information without creating it
// * (a byproduct of calling getLocationInformation).
// * @return true if location information has been extracted.
// * @since 1.2.15
// */
// public final boolean locationInformationExists() {
// return (locationInfo != null);
// }
/**
* Getter for the event's time stamp. The time stamp is calculated starting
* from 1970-01-01 GMT.
* @return timestamp
*
* @since 1.2.15
*/
public final long getTimeStamp() {
return timeStamp;
}
// /**
// * Returns the set of the key values in the properties
// * for the event.
// *
// * The returned set is unmodifiable by the caller.
// *
// * Provided for compatibility with log4j 1.3
// *
// * @return Set an unmodifiable set of the property keys.
// * @since 1.2.15
// */
// public Set getPropertyKeySet() {
// return getProperties().keySet();
// }
// /**
// * Returns the set of properties
// * for the event.
// *
// * The returned set is unmodifiable by the caller.
// *
// * Provided for compatibility with log4j 1.3
// *
// * @return Set an unmodifiable map of the properties.
// * @since 1.2.15
// */
// public Map getProperties() {
// getMDCCopy();
// Map properties;
// if (mdcCopy == null) {
// properties = new HashMap();
// } else {
// properties = mdcCopy;
// }
// return Collections.unmodifiableMap(properties);
// }
// /**
// * Get the fully qualified name of the calling logger sub-class/wrapper.
// * Provided for compatibility with log4j 1.3
// * @return fully qualified class name, may be null.
// * @since 1.2.15
// */
// public String getFQNOfLoggerClass() {
// return fqnOfCategoryClass;
// }
// /**
// * This removes the specified MDC property from the event.
// * Access to the MDC is not synchronized, so this
// * method should only be called when it is known that
// * no other threads are accessing the MDC.
// * @param propName the property name to remove
// * @since 1.2.16
// */
// public Object removeProperty(String propName) {
// if (mdcCopy == null) {
// getMDCCopy();
// }
// if (mdcCopy == null) {
// mdcCopy = new Hashtable();
// }
// return mdcCopy.remove(propName);
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment