import java.io.File;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
import org.apache.log4j.Hierarchy;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.spi.RootLogger;
public class SocketServer {
static String CLIENT_DIR = "client";
static String CONFIG_FILE_EXT = ".properties";
static Logger cat = Logger.getLogger(SocketServer.class);
static SocketServer server;
static int port;// key=application, value=hierarchy
Hashtable<String, Hierarchy> hierarchyMap;
String dir;
public static void main(String argv[]) {
if (argv.length == 2)
init(argv[0], argv[1]);
else
usage("Wrong number of arguments.");
//init("30020", "config");
try {
cat.info("Listening on port " + port);
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
cat.info("Waiting to accept a new client.");
Socket socket = serverSocket.accept();
InetAddress inetAddress = socket.getInetAddress();
cat.info("Connected to client at " + inetAddress);
cat.info("Starting new socket node.");
new Thread(new SocketNode(socket, server.hierarchyMap)).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
static void usage(String msg) {
System.err.println(msg);
System.err.println("Usage: java " + SocketServer.class.getName() + " port configFile directory");
System.exit(1);
}
static void init(String srvPort, String configDir) {
try {
port = Integer.parseInt(srvPort);
} catch (java.lang.NumberFormatException e) {
e.printStackTrace();
usage("Could not interpret port number [" + srvPort + "].");
}
PropertyConfigurator.configure(configDir + File.separator + "socketserver.properties");
server = new SocketServer(configDir);
}
public SocketServer(String configDir) {
this.dir = configDir;
hierarchyMap = new Hashtable<String, Hierarchy>(11);
configureHierarchy();
}
// This method assumes that there is no hiearchy for inetAddress
// yet. It will configure one and return it.
void configureHierarchy() {
File configFile = new File(dir + File.separator + CLIENT_DIR);
if (configFile.exists() && configFile.isDirectory()) {
String[] clients = configFile.list();
for (int i = 0; i < clients.length; i++) {
File client = new File(dir + File.separator + CLIENT_DIR + File.separator + clients[i]);
if (client.isFile()) {
Hierarchy h = new Hierarchy(new RootLogger(Level.DEBUG));
String application = clients[i].substring(0, clients[i].indexOf("."));
cat.info("Locating configuration file for " + application);
hierarchyMap.put(application, h);
new PropertyConfigurator().doConfigure(client.getAbsolutePath(), h);
}
}
}
}
}
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.Hashtable;
import org.apache.log4j.Hierarchy;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
// Contributors: Moses Hohman <mmhohman@rainbow.uchicago.edu>
/**
* Read {@link LoggingEvent} objects sent from a remote client using Sockets
* (TCP). These logging events are logged according to local policy, as if they
* were generated locally.
*
* <p>
* For example, the socket node might decide to log events to a local file and
* also resent them to a second socket node.
*
* @author Ceki Gülcü
*
* @since 0.8.4
*/
public class SocketNode implements Runnable {
Socket socket;
ObjectInputStream ois;
Hashtable<String, Hierarchy> hashtable;
static Logger logger = Logger.getLogger(SocketNode.class);
public SocketNode(Socket socket, Hashtable<String, Hierarchy> hashtable) {
this.socket = socket;
this.hashtable = hashtable;
try {
ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
} catch (Exception e) {
logger.error("Could not open ObjectInputStream to " + socket, e);
}
}
// public
// void finalize() {
// System.err.println("-------------------------Finalize called");
// System.err.flush();
// }
public void run() {
LoggingEvent event;
Logger remoteLogger;
try {
if (ois != null) {
while (true) {
// read an event from the wire
event = (LoggingEvent) ois.readObject();
Object application = event.getMDC("application");
if (application != null) {
// get a logger from the hierarchy. The name of the
// logger
// is taken to be the name contained in the event.
remoteLogger = hashtable.get(application).getLogger(event.getLoggerName());
// logger.info(remoteLogger.getAppender(application.toString()));
// event.logger = remoteLogger;
// apply the logger-level filter
if (remoteLogger != null && event.getLevel().isGreaterOrEqual(remoteLogger.getEffectiveLevel())) {
// finally log the event as if was generated locally
remoteLogger.callAppenders(event);
}
}
}
}
} catch (java.io.EOFException e) {
logger.info("Caught java.io.EOFException closing conneciton.");
} catch (java.net.SocketException e) {
logger.info("Caught java.net.SocketException closing conneciton.");
} catch (IOException e) {
logger.info("Caught java.io.IOException: " + e);
logger.info("Closing connection.");
} catch (Exception e) {
logger.error("Unexpected exception. Closing conneciton.", e);
} finally {
if (ois != null) {
try {
ois.close();
} catch (Exception e) {
logger.info("Could not close connection.", e);
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException ex) {
}
}
}
}
}
#文件名socketserver.properties
log4j.rootCategory=INFO, STDOUT log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=[%d{yyyy-MM-dd HH\:mm\:ss}][%5p][%5t][%l] %m%n
|
#文件名test.properties
log4j.rootLogger=info,test log4j.category.org.springframework.jdbc=debug,test
log4j.category.test=debug,test
log4j.additivity.test=false
log4j.additivity.org.springframework.jdbc=false
log4j.appender.test=org.apache.log4j.DailyRollingFileAppender
log4j.appender.test.DatePattern='.'yyyy-MM-dd
log4j.appender.test.File=${logPath}/test/bmr.log
log4j.appender.test.Append=true
log4j.appender.test.Threshold=INFO
log4j.appender.test.layout=org.apache.log4j.PatternLayout
log4j.appender.test.layout.ConversionPattern=[%d{yyyy-MM-dd HH\:mm\:ss}][%5p][%5t][%l] %m%n
|
日志服务器的启动脚本LogServer.bat
@echo off
java -cp .\log4j-1.2.8.jar -DlogPath=D:\LogServer\log *****.SocketServer 30020 config |
log4j.rootCategory=, test
log4j.appender.test=org.apache.log4j.net.SocketAppender
log4j.appender.test.RemoteHost=“日志计算机” log4j.appender.test.Port=30020 log4j.appender.test.application=test |