给聊天记录加上日志

聊天往往需要把聊天记录保存下来,可以用Log4j实现,具体代码如下

package Net.TCP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class TCPPoolLogServer {

	transient ServerSocket server;
	  // 构造一个线程池
	static transient Logger log = Logger.getLogger("TCPPoolServerLog");
	
	static
	{
		PropertyConfigurator.configure("log4j.properties");
	}

    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 4, 3, TimeUnit.SECONDS, new ArrayBlockingQueue(3),
            new ThreadPoolExecutor.DiscardOldestPolicy());
    
	public static void main(String[] args) throws IOException {
		TCPPoolServer tcpserver=new TCPPoolServer();
		ServerSocket server=new ServerSocket(30006);
		while(true)
		{
			System.out.println("服务器等待中.......");
			final Socket socket=server.accept();
			ClientJobLog job=new ClientJobLog(socket);
			tcpserver.threadPool.execute(job);
		}
	}

	static void doClient(Socket socket) throws IOException
	{
		System.out.println("接收到一个客户端信号LOG"+socket.getInetAddress().getHostAddress()+"  名称是: "+socket.getInetAddress().getHostName());
		BufferedReader fromClient=new BufferedReader(new InputStreamReader(socket.getInputStream()));
		BufferedReader message=new BufferedReader(new InputStreamReader(System.in));
		String line=fromClient.readLine();
		while(line!=null&&!line.equals("exit"))
		{
			System.out.println(socket.getInetAddress().getHostAddress()+":"+line);
			line=fromClient.readLine(); 
			log(socket.getInetAddress().getHostAddress(),line);
		}

		System.out.println(socket.getInetAddress().getHostAddress()+"退出");
		message.close();
		fromClient.close();
	}

	static void log(String talker,String msg)
	{
		log.info("\n"+talker+":\n"+"               "+msg);
	}
}

 

log4j配置如下:

 

log4j.rootLogger = stdout

log4j.appender.stdout = org.apache.log4j.DailyRollingFileAppender
log4j.appender.stdout.File = E://EclipseProject/ACM/log/qq.log
log4j.appender.stdout.Append = true
log4j.appender.stdout.Threshold = DEBUG
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern =  %d{yyyy-MM-dd HH:mm:ss,SSS}   %m%n

 

打印出来结果如下:

192.168.100.156:

2016-01-09 17:14:57,595                  说话

192.168.100.156:

2016-01-09 17:14:59,293                  好

 

 


 

你可能感兴趣的:(网络编程,log4j)