1、而且,通过使用各种第三方扩展,您可以很方便地将Log4j集成到J2EE、JINI甚至是SNMP应用中。本文介绍的Log4j版本是1.2.3。作者试图通过一个简单的客户/服务器Java程序例子对比使用与不使用Log4j 1.2.3的差别,并详细讲解了在实践中最常使用Log4j的方法和步骤。在强调可重用组件开发的今天,相信Log4j将会给广大的设计开发人员带来方便。加入到Log4j的队伍来吧!回页首一个简单的例子我们先来看一个简单的例子,它是一个用Java实现的客户/服务器网络程序。刚开始我们不使用Log4j,而是使用了一系列的打印语句,然后我们将使用Log4j来实现它的日志功能。这样,大家就可以
2、清楚地比较出前后两个代码的差别。2.1. 不使用Log4j2.1.1. 客户程序 package log4j ;import java.io.* ;import .* ;/* * * Client Without Log4j Description: a sample with log4j * version 1.0 */public class ClientWithoutLog4j /* * param args public static void main ( String args ) String welcome = null; String response = null; Buf
3、feredReader reader = null; PrintWriter writer = null; InputStream in = null; OutputStream out = null; Socket client = null; try client = new Socket ( localhost, 8001 ) ; System.out.println ( info: Client socket: + client ) ; in = client.getInputStream () ; out = client.getOutputStream () ; catch ( I
4、OException e ) error: IOException : + e ) ; System.exit ( 0 ) ; try reader = new BufferedReader( new InputStreamReader ( in ) ) ; writer = new PrintWriter ( new OutputStreamWriter ( out ), true ) ; welcome = reader.readLine () ;debug: Server says: + welcome + ) ; HELLO writer.println ( HELLO respons
5、e = reader.readLine () ; Server responds: + response + ) ; HELPHELP QUITQUITwarn: IOException in client.in.readln() System.out.println ( e ) ; Thread.sleep ( 2000 ) ; catch ( Exception ignored ) 2.1.2. 服务器程序 import java.util.* ; Server Without Log4j public class ServerWithoutLog4j final static int S
6、ERVER_PORT = 8001 ; / this servers port String clientRequest = null; ServerSocket server = null; Socket socket = null; server = new ServerSocket ( SERVER_PORT ) ; ServerSocket before accept: + server ) ; Java server without log4j, on-line! / wait for clients connection socket = server.accept () ; Se
7、rverSocket after accept: in = socket.getInputStream () ; out = socket.getOutputStream () ; System.out.println( Server constructor IOException: reader = new BufferedReader ( new InputStreamReader ( in ) ) ; writer = new PrintWriter ( new OutputStreamWriter ( out ) , true ) ; / send welcome string to
8、clientJava server without log4j, + new Date () ) ; while ( true ) / read from client clientRequest = reader.readLine () ; Client says: + clientRequest ) ; if ( clientRequest.startsWith ( ) ) OK!Vocabulary: HELP QUIT else else Command + clientRequest + not understood.Command + clientRequest + IOException in Server 2.2. 迁移到Log4j2.2.1. 客户程序 / add for log4j: import some packageimport org.apache.log4j.PropertyConfigurator ;import org.apache.log4j.Logger ;import org.apache.log4j.Level ; Client With Log4j a sample with log
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1