在服务器集群中,如果想要集中管理服务器上的日志,可以使用log4j提供的一个远程日志Appender--SocketAppender。且如果需要按不同的业务,也可自定义存放到不同的文件中。具体log4j的配置及代码如下:
服务器端:
log4j.properties
log4j.log4j.rootLogger= INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.logger.myTest1= DEBUG, test1
log4j.appender.test1=org.apache.log4j.FileAppender
log4j.appender.test1.File=D:/log/test1.log
log4j.appender.test1.layout=org.apache.log4j.PatternLayout
log4j.appender.test1.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.logger.myTest2= DEBUG, test2
log4j.appender.test2=org.apache.log4j.FileAppender
log4j.appender.test2.File=D:/log/test2.log
log4j.appender.test2.layout=org.apache.log4j.PatternLayout
log4j.appender.test2.layout.ConversionPattern=%d %p [%c] - %m%n
服务器代码:
package com.yss.demo.log2;
import java.net.InetAddress;
public class Server extends Thread {
private static final int DEFAULT_PORT = 4560;
private final int port;
public Server(int port) {
this.port = port;
}
public Server() {
this(DEFAULT_PORT);
}
@Override
public final void run() {
try {
Logger cat = Logger.getLogger(Server.class);
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);
LoggerRepository h = LogManager.getLoggerRepository();
cat.info("Starting new socket node.");
// TODO: can we use information in the socket to record the client host?
new Thread(new SocketNode(socket, h)).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Server().start();
}
}
客户端:
log4j.properties
log4j.rootLogger=info,socket
log4j.appender.socket=org.apache.log4j.net.SocketAppender
log4j.appender.socket.RemoteHost=localhost
log4j.appender.socket.Port=4560
log4j.appender.socket.LocationInfo=true
客户端代码:
import org.apache.log4j.Logger;
public class Client {
public static void main(String[] args) throws Exception {
Logger logger = Logger.getLogger("myTest1");
logger.info("wwwwwww11111111");
Logger logger2 = Logger.getLogger("myTest2");
logger2.info("wwwwwww2222222");
}
}
log4j默认使用的配置是类路径下的log4j.properties,如果客户端和服务器端代码在同一个项目下时,就需要分别为各自的log4j配置文件重新命名,以示区分,并在获取Logger之前使用
PropertyConfigurator.configure("Log4JConfig_client.properties");
这种方式加载指定的配置文件,这样才可使各自的代码、配置生效。