log4j 多进程写问题

可以使用socketappender解决多进程写问题。

server端代码:

package log4j; import org.apache.log4j.Logger; import
org.apache.log4j.net.SimpleSocketServer; public class Server{ static Logger
cat = Logger.getLogger(SimpleSocketServer.class); public static void
main(String[] args){ System.out.println(“Accessing socket on localhost:6666”);
String[] g = {“6666”, “test.properties”}; SimpleSocketServer.main(g); } }

server端的配置文件test.properties:

log4j.rootLogger=debug,stdout,R

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

Pattern to output the caller’s file name and line number.

log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=remote_log.log

log4j.appender.R.MaxFileSize=1024KB

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

client端代码:

package log4j; import org.apache.log4j.Level; import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator; import
org.apache.log4j.net.SocketAppender; import org.apache.log4j.spi.LoggingEvent;
public class Client1{ static Logger logger = Logger.getRootLogger(); public
static void main(String argv[]) { // Try sending logging events through the
SocketAppender in the log4j_remote.properties file System.out.println(“Try
sending logs through the SocketAppender in the log4j.properties file”);
PropertyConfigurator.configure(“client.properties”); //Logs to a
SocketAppender; host 127.0.0.1, port 4445 logger.debug(“Hello world”);
logger.info(“What a beatiful day.”); // And try sending logging events through
SocketAppender instance System.out.println(“Try sending logs through a
SocketAppender instance”); SocketAppender sa = new SocketAppender(“localhost”,
6666); System.out.println(“Created SocketAppender instance”); String logMsg =
“Writing log event through SocketAppender instance”; LoggingEvent le = new
LoggingEvent(“TestLog4J”, Logger.getRootLogger(), Level.DEBUG, logMsg, new
Throwable()); sa.append(le); //sa.close(); } }

client端的配置文件client.properties:

log4j.rootCategory=DEBUG,stdout,A1

ConsoleAppender

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

Pattern to output the caller’s file name and line number.

log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

A1 is set to be a SocketAppender sending its output to the server running on

the remote host, port 12345.
log4j.appender.A1=org.apache.log4j.net.SocketAppender
log4j.appender.A1.Port=6666
log4j.appender.A1.RemoteHost=localhost