블로그 이미지
좋은느낌/원철
이것저것 필요한 것을 모아보렵니다.. 방문해 주셔서 감사합니다..

calendar

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Notice

    2008. 6. 24. 15:20 개발/UNIX 계열

    AIX 점검 명령어

    CPU - 수량 및 사용 가능상태 확인
    lsdev -Cc processor Processor 수량 및 Available 한 가용상태 확인

    CPU - CPU의 병목 여부 파악
    sar Processor 별로 사용률 점검
    vmstat processor 의 used, idle, wait 등을 파악
    topas processor load average 를 검토
    bindprocessor processor bind 의 존재여부 확인 및 필요 시 binding

    Memory - 수량 및 사용 가능상태 확인
    lsdev -Cc Memory memory(Card)수량 및 Available 한 가용상태 확인
    lsattr -El mem(n) 메모리 타입 및 Size 확인

    Disk - 수량 및 사용 가능상태 확인
    lsdev -Cc disk disk 수량 및 Available 한 가용상태 확인
    lspv 디스크 할당 상태 확인
    lspv hdisk(n) 디스크 할당 상태 및 가용 Size 확인

    Adapter - 구성된 종류 및 수량, 가용상태 확인
    lsdev-Cc adapter adapter 별 Available 한 가용상태 확인
    diag 구성 장치들의 문제점 진단

    Log 점검 - 오류에 대한 로그 및 시스템에 설정된 로그파일 확인
    errpt System 에서 발생된 기본적인 로그를 확인하고 Class:H (Hardware)와 type:P(PEND, PERF, PERM) 부분의 발생여부 중점으로 점검
    vi /var/spool/mail/root root 메일을 점검하여 관리자에게 통지된 에러 확인
    find / -name core core 파일 생성 여부 확인

    Memory - Memory의 과부하 여부 파악
    vmstat 충분한 Free memory가 있는지 확인하고 paging in, out 여부를 파악하여 Memory의 병목 여부 판단.
    lsps Paging 공간의 사용률을 파악하여 메모리 병목 판단에 활용
    topas Memory의 caching 사용여부와 사용률을 파악
    ps aux 프로세스 별로 메모리 사용률 파악
    svmon 프로세스 사용률 순 또는 Memory 사용률에 따른 순서로 상세한 사용에 대한 세부 내역파악.

    posted by 좋은느낌/원철
    2008. 6. 24. 15:18 개발/UNIX 계열
    [AIX] 시스템 정보 명령어 모음
     
     
    1. 제조사  
       - 회사명 = lsattr -El sys0
       - 모델명 = prtconf (하드웨어config)
     
    2. OS version
       - 버전 = oslevel -r
     
    3. CPU 
       - Arch = prtconf
       - Hz   = lsattr -El proc0 (단위 Hz)
       - 개수 = lsdev -Cc processor|wc -l
      
    4. Memory
       - 용량 = lsattr -El sys0, prtconf
     
    5. Virtual Memory
       - 용량 = lsps -a
     
    6. Internal Disk
       - size = bootinfo -s hdisk(숫자) (Mb단위)
       - 개수 = lsdev -Cc disk
     
    7. External Disk (SSA)
       - size = bootinfo -s hdisk(숫자) (Mb단위)
       - 개수 = lsdev -Cc pdisk , lsdev -Ct hdisk
     
    8. rootvg mirror(y/n)
       - not mirror = lsvg rootvg (ACTIVE PVs = 1)
       - mirror     = lsvg rootvg (ACTIVE PVs = 2)
     
    9. NIC
       - 속도, 개수 = lsparent -Ck ent
     
    10. 시스템에 장착된 부품들에 위치확인
       - lscfg -vp
     
    * 일반적 정보
    prtconf                      = list system configuration
    lscfg [-v]                  = devices (-v = verbose for microcode levels, etc)
    lscfg -v                     = devices verbose (microcode level, firmware, etc)
    lsdev -Cc adapter      = adapter cards
    lsdev -Cc disk           = disks
    lsdev -Cc processor  = CPU s
    lsattr -El sys0            = serial number, model number, memory
    * AIX 관련 정보
    oslevel                      = AIX OS level
    instfix -i |grep ML      = AIX maintenance level
    lslpp -l                      = installed SW and levels
    * Disk 관련 정보
    lsvg -o                      = active volume groups
    lsvg -p vgname          = disk drives in VG
    lsvg -l vgname           = LV s in VG
    lslv lvname                = LV detail
    lslv -l lvname             = LV disk location
    lspv                          = disks
    lspv -l hdisk#             = LV s residing on a disk

    * Network 관련 정보
    lsdev -Cc if               = List network interfaces
    netstat -rn                 = List network gateways

    출처 : http://ssyangcal.tistory.com/414
    posted by 좋은느낌/원철
    2008. 6. 24. 09:42 개발/Java

    이클립스 설치후 깔아야할 플러그인들 ..

    ( 현재 Eclipse 3.2.x 기준 )

    1. 기본적으로 WTP 플러그인을 설치한다.
        (Update 실행하면 됨 ㅋㅋ)

    2. AnyEdit 말이 필요 없다. 필수!
    - Ctrl + Alt + R 누르면 해당 링크로 바로 이동 ㅡ_ㅡ; 소스레벨의 F3키와는 다른 편리함 이밖에도 다른 기능들이 조낸 많음
    - 사이트 :  http://andrei.gmxhome.de/anyedit/index.html
    - 업데이트 : http://andrei.gmxhome.de/eclipse/

    3. properEdit
    - 각종 property 파일 수정할때 native2ascii 할 필요가 없게 해주는 유용함. ㅋ 일본어, 한글, utf-8 다 지원한다.

    4. Extended VS Presentation
    - 이클립스 스타일을 변경해줌과 동시에 인터페이스가 바뀐다 ㅡㅡ; 지금 랭킹 1위야 ㅡㅡ; 그밖에 여러가지
    - 사이트: http://andrei.gmxhome.de/skins/index.html
    - 업데이트 : http://andrei.gmxhome.de/eclipse/

    5. QuickREx - regular expressions
    - 웹개발을 하다보면 말이지 레귤러 익스프레션을 사용할 일이 생긴다고 ㅡㅡ; 요거 그거야 ㅋ
    - 사이트 : http://www.bastian-bergerhoff.com/eclipse/features/web/QuickREx/toc.html 
    - 업데이트 : http://www.bastian-bergerhoff.com/eclipse/features

    6. Log4E
    -  말안해도 알겠쥐?
    - 사이트 : http://log4e.jayefem.de
    - 업데이트 : http://log4e.jayefem.de/update

    7. Oxygen XML Editor and XSLT Editor/Debugger
    - XML 써바야지 ㅡㅡ;
    - 사이트 : http://www.oxygenxml.com
    - 업데이트 : http://www.oxygenxml.com/InstData/Eclipse

    8. JadClipse
    -  이건 역컴파일러라는거지 ㅎㅎ 넘 괜찮은넘 ㅡㅡ;
    - 사이트 : http://jadclipse.sourceforge.net/
    - 업데이트 :

    9. PMD For Eclipse
    -
    - 사이트 : http://pmd.sourceforge.net/
    - 업데이트 : http://pmd.sourceforge.net/eclipse/

    10. Code Analysis Plugin - CAP
    -  요건 페키지, 파일 들이 어떤 구조로 되어 있는지 한눈에 알 수 있게 해준다. 스크린샷 참고
    - 사이트 : http://cap.xore.de
    - 업데이트 : http://cap.xore.de/update/

    11. Checkstyle Plug-in
    - 알려진 소스에 대한 스타일 체크
    - 사이트 : http://eclipse-cs.sourceforge.net/
    - 업데이트 : http://eclipse-cs.sourceforge.net/update

    12. QuantumDB Eclipse Plugin
    - SQL
    - 사이트 : http://quantum.sourceforge.net/
    - 업데이트 :
    파일다운로드




    13. Maven Integration for Eclipse
    - 마빈 플러그인 이클립스에서 마빈을 사용하여 빌드를 할 수 있게 해준다 .. ㅋㅋ 필수조 ㅎㅎ
    - 사이트 : http://m2eclipse.codehaus.org/
    - 업데이트 : http://m2eclipse.codehaus.org/update/

    14. Lib Copy
    - 마빈 플러그인 이클립스에서 마빈을 사용하여 빌드를 할 경우 WTP와 통합이 되도록 해준다 ㅋㅋ 자세한 사항은 아래 사이트 참조 ( 이건 WTP를 사용 하지 않을꺼라면(대신 sysdo tomcat plugin 사용) 안해도 된다)
    - 사이트 : http://adam.kruszewski.name/projects/libcopy
    - 업데이트 : http://adam.kruszewski.name/eclipse

    15. Sysdeo Eclipse Tomcat Launcher plugin
    -  톰켓 플러그인
    - 사이트 : http://www.sysdeo.com/eclipse/tomcatplugin
    - 업데이트 :  톰켓 6.0 까지 지원 아직 배타이지만 정식 나오겠지 (압축풀어 설치)
    파일 다운 로드



    16. SubVersion 버전 관리 툴
    - 버전 관리 막강한 client 툴 이거 없으면 못해 CVS도 있지만 서브 버전의 막강한 기능을 구현
    - 사이트 : http://www.polarion.org/p_subversive_features.php
    - 업데이트 : http://www.polarion.org/download/p_subversive/update-site/



    ■ 이클립스 플러그인 관련 사이트

    http://www.eclipse-plugins.info/ 간단한 플러그인 정보와 인기도(?) 확인 가능
    http://www.sourceforge.net/ 각종 이클립스 플러그인 프로젝트들이 등록되어있음
    http://www.eclipseplugincentral.com/ 플러그인 쇼핑몰, 포럼


    ■ DB 플러그인

    1) Quantum DB (http://sourceforge.net/projects/quantum/)

    왼쪽 북마크에 접속하고자 하는 DB 추가하고 환경잡기(ID, 비번, 접속드라이버 등)
    원하는 북마크를 오른쪽버튼 클릭해서 DB에 connect한 후 오른쪽 쿼리 에디터에서 쿼리.

    [참고]
    - 오라클 JDBC드라이버 : C:oracleora81jdbclibclases12.zip 찾아서 추가 (oracle.jdbc.driver.OracleDriver)
    - connection URL : jdbc:oracle:thin:@000.00.00.000:1521:ORACLE8

    2) dbedit (http://sourceforge.net/projects/dbedit/)

    3) jfacedbc #상용# (http://sourceforge.net/projects/jfacedbc/)

    소스포지에 있는 버전은 2.X 버전이고 3.0부터는 상용으로 http://www.jfacedbc.com/ 에서 다운/구매 가능 (기능은 확실히 좋을 듯...)



    ■ XML 플러그인

    1) XMLBuddy http://www.xmlbuddy.com/
    XMLBuddy pro는 #상용#입니다.

    2) oxygen #상용#
    url update : http://www.oxygenxml.com/InstData/Eclipse/site.xml

    3) MyEclipse Enterprise Workbench #상용# (http://www.myeclipseide.com/)
    MyEclipse 설치하면 깔리는 XML 에디터.

    4) 그 외 JXMLEditor, MetaCoder , Sunbow , X-Men, XML Schema Quality Checker



    ■ J2EE 개발 플랫폼

    1) Lomboz (http://forge.objectweb.org/projects/lomboz)
    롬보즈를 쓰기 위해서는 EMF(http://www.eclipse.org/emf)도 깔려있어야 함

    2) MyEclipse Enterprise Workbench #상용# (http://www.myeclipseide.com/)



    ■ JSP 에디터 플러그인

    1) SolarEclipse (http://sourceforge.net/projects/solareclipse/)
    jsp 하이라이팅 기능만 있음

    2) Lomboz jsp editor (http://forge.objectweb.org/projects/lomboz)
    롬보즈 설치하면 깔리는 jsp 에디터. 코드 어시스턴스 기능 있음.

    3) MyEclipse Enterprise Workbench #상용# (http://www.myeclipseide.com/)
    MyEclipse 설치하면 깔리는 jsp 에디터. 롬보즈가 저장 시 에러 체크를 하는 반면, 실시간으로 에러 체크를 한다고 함.



    ■ 각종 플러그인

    1) Yoxos ( http://www.yoxos.com/ )

    유용한 플러그인들을 묶어 프로그램 인스톨하는 형식으로 배포.
    종류별로 잘 분류되어 있고 설치시 필요한 플러그인만 선택하여 설치 가능.

    2) subversion (svn) 플러그인
    url update : http://subclipse.tigris.org/update

    3) SWT/Swing 디자이너 #상용# http://www.swt-designer.com/




    ■ 플러그인 설치

    1) 설치유형 1 : 복사
    받은 플러그인 파일을 C:eclipseplugins 에 복사하고 재시작

    2) 설치유형 2 : url update
    Help > Software Updates > Find and Install 메뉴 선택
    "search for new features to install" 선택후 next 버튼
    new remote site 버튼을 클릭하여 플러그인명과 url update 주소를 입력하면 다운 받을 수 있다.

    3) 플러그인 설치 문제 해결

    복사해서 플러그인을 설치 할 때 가끔 반영이 안되는 문제가 있다.
    똑같이 설치를 해도 잘 되는 컴이 있는가 하면 그렇지 않은 것도 있으니... -_-a
    처음 실행 이전에 플러그인을 모두 복사해야 정상작동할 듯 싶다. 일단 실행 이후에 플러그인을 추가 설치하면 간혹 말썽이다.

    첫째, Help > Software Updates > Manage Configuration 에서 설치되지않은 것들이 있으면 enable 시켜준다.
    이렇게 해서 해결 된다면 제일 편하게 해결된 것.

    둘째, eclipse 폴더 아래 configuration 폴더를 지우고 재시작.

    셋째, 이래도 안 깔리면.... 이클립스를 아예 새로 풀고 플러그인들 먼저 다 복사해 둔 후 최초실행 시킨다.



    자료출처 : http://www.cyworld.com/kangs007
    posted by 좋은느낌/원철
    2008. 6. 17. 14:23 개발/Java
    출처 : http://www.ibm.com/developerworks/kr/forums/dw_thread.jsp?forum=26&thread=2517&cat=4

    commons-configuration 를 이용한 프로그램 설정 다루기
     

    대부분의 프로그램들에서 설정이라는 것이 필요하다.
    간단히 웹서버의 예를 들면...
    - 어떤 포트를 사용할 것인지
    - 홈 디렉토리 지정
    - DB 연동시 JDBC 드라이버 지정 및 URL 과 계정 정보
    이런 것들이 필요할텐데 간단히 프포퍼티 파일을 만들어서 JDK에서 기본으로 제공되는
    프포퍼티 클래스를 이용할 수도 있다. 그러나 JDK에서 기본으로 제공되는 클래스는
    기능이 단순하고 제한적이다. 예를 들어 스트링 타입으로만 처리되기 때문에 다른 타입의
    값을 원할때는 개발자가 모두 처리를 해주어야 한다. 또한 한글 처리도 매끄럽지 못하다.
    이런 이유들로 인해 간단한 설정 처리 프로그램을 만드는데에도 에러가 많아지고 그에 따는
    시간과 노력이 들어가게 된다. 그러나 걱정할 필요가 없다. commons-configuration 를
    이용하면 이런 대부분의 노력이 필요 없게 된다.
    애래에서처럼 프로퍼티 파일을 만들고 자바 프로그램을 실행시켜보면
    commons-configuration 의 일부 기능이지만 얼마나 좋은 것인지 알게 될 것이다.

    * commons-configuration 은 다른 라이브러리들에 의존성이 있다.
    commons-logging, commons-lang, commons-collections 라이브러리들도 포함시킨다.

    * test.prop 파일의 내용
    project.home = D:/dev/commons-configuration
    port = 8080
    debug = false
    temp.home = D:/새 폴더

    jdbc.driver = com.mysql.jdbc.Driver
    jdbc.driver = jdbc.odbc.JdbcOdbcDriver
    jdbc.driver = oracle.jdbc.driver.OracleDriver
    jdbc.driver = com.sybase.jdbc.SybDriver

    mysql.host = localhost
    mysql.db = test
    mysql.user =


    * 프로그램 소스
    import org.apache.commons.configuration.Configuration;
    import org.apache.commons.configuration.PropertiesConfiguration;

    public class PropertyTest {
    Configuration config;

    public void load() {
    try {
    // 프로퍼티 파일 로딩
    this.config = new PropertiesConfiguration("test.prop");
    }
    catch (org.apache.commons.configuration.ConfigurationException e) {
    System.err.println(e.getMessage());
    }
    }

    public void test() {
    try {
    String projectHome = config.getString("project.home");
    System.out.println("project.home = [" + projectHome + "]");

    // int primitive type, int 타입으로 즉시 사용 가능
    int port = config.getInt("port");
    System.out.println("port = [" + port + "]");

    // boolean primitive type, boolean 타입으로 즉시 사용 가능
    boolean debug = config.getBoolean("debug");
    System.out.println("debug = [" + debug + "]");

    // 한글도 이상 없다
    String tempHome = config.getString("temp.home");
    System.out.println("temp.home = [" + tempHome + "]");

    // String array type, 키와 값이 쌍으로 배열처럼 처리
    String[] jdbcDrivers = config.getStringArray("jdbc.driver");
    for (int i = 0; i < jdbcDrivers.length; i++) {
    System.out.println("[" + jdbcDrivers + "]");
    }

    // 값이 지정되어 있지 않는 경우, 예외를 발생하지 않는다
    String mysqlUser = config.getString("mysql.user");
    System.out.println("mysql.user = [" + mysqlUser + "]");

    // 키가 존재하지 않는 경우, 키가 존재하지 않는 경우에 값이 null
    String mysqlPassword = config.getString("mysql.password");
    System.out.println("mysql.password = [" + mysqlPassword + "]");

    // 키가 존재하지 않더라도 기본값을 지정되는 경우
    String defaultPassword = config.getString("mysql.password", "admin");
    System.out.println("mysql.password = [" + defaultPassword + "]");

    }
    catch (org.apache.commons.configuration.ConversionException e) {
    System.err.println(e.getMessage());
    }
    }

    public static void main(String[] args) {
    PropertyTest prop = new PropertyTest();
    prop.load();
    prop.test();
    }

    }

    * 실행 결과
    project.home = [D:/dev/commons-configuration]
    port = [8080]
    debug = [false]
    temp.home = [D:/새 폴더]
    [com.mysql.jdbc.Driver]
    [jdbc.odbc.JdbcOdbcDriver]
    [oracle.jdbc.driver.OracleDriver]
    [com.sybase.jdbc.SybDriver]
    mysql.user = []
    mysql.password = [null]
    mysql.password = [admin]

    posted by 좋은느낌/원철
    2008. 6. 17. 10:18 개발/Java
    [펌]log4j 설정법
    [출처]http://jami.tistory.com/entry/%ED%8E%8Clog4j-%EC%84%A4%EC%A0%95%EB%B2%95
    참고파일



    =============================================

    본문서는 자유롭게 배포/복사 할수 있지만

    이문서의 저자에 대한 언급을 삭제하시면 안됩니다

    저자 : GoodBug (unicorn@jakartaproject.com)

    최초 : http://www.jakartaproject.com 

    =============================================


    LOG4J

    I. 들어가면서.. 그리고 log4j


    log4j는 자바 어플리케이션에서 빠르고 효과적으로 로깅 할 수 있도록 도와주는 오픈 소스 프로젝트입니다.


    로깅(logging)은 코드의 가독성을 떨어뜨리는 단점이 있지만 애플리케이션에 문제가 있을 때 개발자가 자세한 상황을 파악할 수 있도록 해 주며 테스팅시 빠질 수 없는 요소입니다.


    아마도 여러분들은 여러 어플리케이션이 추가되면서 각 개발자들만의 독특한 로깅방식이 서로 썩이고 얽혀서 화면에 나타나는것을 많이 봤을겁니다 -_-;
    즉 로깅방법을 통일할 필요가 있는것이죠. 모든 개발자가 특정 포맷에 맞추어서 로깅 한다면 한결 로깅하기도 편하겠지요


    오픈 소스 프로젝트인 Log4j는 개발자들이 매우 손쉽고 다양한 형태로 로깅을 할 수 있도록 도와줍니다. 성능또한 우수해 더이상 System.out.println을 사용할 필요가 없습니다.



    II. 다운로드


    다운로드 http://logging.apache.org/log4j/docs/download.html

    매뉴얼 http://logging.apache.org/log4j/docs/documentation.html

    API spec http://logging.apache.org/log4j/docs/api/index.html



    III. LOG4J 구조


    일단 log4j를 잘 모르지만 그 구조만 살짝 살펴보고 넘어갑시다

    log4j는 크게 3가지 요소로 구성되며 그 구조는 다음과 같습니다

    ① Logger(Category) : 로깅 메세지를 Appender에 전달합니다.

    ② Appender : 전달된 로깅 메세지를 파일에다 기록할 것인지, 콘솔에 출력할 것인지

                       아니면 DB에 저장할 것인지 매개체 역활을 합니다.

    ③ Layout : Appender가 어디에 출력할 것인지 결정했다면 어떤 형식으로 출력할 것이지

                    출력 layout을 결졍합니다.

    쉽죠?



    IV. LOG4J 로깅 레벨


    log4j는 다양한 로깅레벨을 지원합니다.


    ① FATAL : 가장 크리티컬한 에러가 일어 났을 때 사용합니다.

    ② ERROR : 일반 에러가 일어 났을 때 사용합니다.

    ③ WARN : 에러는 아니지만 주의할 필요가 있을 때 사용합니다.

    ④ INFO : 일반 정보를 나타낼 때 사용합니다.

    ⑤ DEBUG : 일반 정보를 상세히 나타낼 때 사용합니다.


    만약 로깅 레벨을 WARN 으로 설정하였다면 그 이상 레벨만 로깅하게 됩니다.

    즉 WARN, ERROR, FATAL 의 로깅이 됩니다.



    V. 샘플코드 1


    jsp에서 사용하는 예제가 없어 만들어 봤습니다.


    test.jsp


    <%@ page contentType="text/html;charset=MS949"
     import="org.apache.log4j.Logger" %>

    <%!
     static Logger logger = Logger.getLogger("test.jsp");
    %>

    <%
    logger.fatal("fatal!!");

    logger.fatal("fatal2!!", new NullPointerException("널입니다요"));

    logger.error("error!", new NumberFormatException());

    logger.error("error!2");

    logger.warn("warn");

    logger.info("info");

    logger.debug("debug");
    %>


    결과 콘솔화면








    static Logger logger = Logger.getLogger("test.jsp");

    static 메소드 getLogger를 통해 logger 인스턴스를 가져옵니다.
    getLogger에는 파라미터로 스트링 혹은 클래스를 사용하는데 jsp에서는 클래스를 파라미터로 주기에는 좀 애매합니다. 그냥 스트링으로 주도록 하지요


    logger.fatal("fatal!!");
    logger.fatal("fatal2!!", new NullPointerException("널입니다요"));
      
    logger에 fatal 레벨의 메세지를 전달합니다. 다음 두가지 메소드를 지원하는군요

    fatal(Object message)

    fatal(Object message, Throwable t)

    각 레벨마다 위처럼 두가지 메소드를 지원합니다.


    지원 메쏘드
    logger.fatal(Object message) logger.fatal(Object message, Throwable t)
    logger.error(Object message) logger.error(Object message, Throwable t)
    logger.warn(Object message) logger.warn(Object message, Throwable t)
    logger.info(Object message) logger.info(Object message, Throwable t)
    logger.debug(Object message) logger.debug(Object message, Throwable t)


    VI. 샘플코드 2


    서블릿의 경우 다음과 같이 코딩하면 되겠군요

    TestServlet.java


    import javax.servlet.*;
    import javax.servlet.http.*;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;

    public class TestServlet extends HttpServlet {


        static Logger logger = Logger.getLogger(TestServlet.class);


        public void init(ServletConfig config) throws ServletException {
             super.init(config);
        }


        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

             try {
                  ...
       
                  logger.info("Hellow World~");

                  ...

              } catch (Exception e) {
                  logger.error("Error at TestServlet", e);
              }
         }
    }



    VII. LOG4J 설정


    log4j 설정은 프로그램 내에서 할 수 있지만 설정파일을 사용함으로서 좀더 유연하게 log4j환경을 만들 수 있습니다.


    프로그램에서 설정

    <%@ page contentType="text/html;charset=MS949"
     import="org.apache.log4j.*,java.io.* "
    %>

    <%!
     static Logger logger = Logger.getLogger("log4j.jsp");
    %>

    <%
    String layout = "%d %-5p [%t] %-17c{2} (%13F:%L) %3x - %m%n";
    String logfilename = "DailyLog.log";
    String datePattern = ".yyyy-MM-dd ";

    PatternLayout patternlayout = new PatternLayout(layout);
    DailyRollingFileAppender appender = new DailyRollingFileAppender(patternlayout, logfilename, datePattern);
    logger.addAppender(appender);
    logger.setLevel(Level.INFO);
    logger.fatal("fatal!!");
    %>


    property 파일에 설정
    log4j.properties를 만들어 /WEB-INF/classes 밑에 놓으세요



    log4j.rootLogger=INFO, stdout, rolling

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

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

    log4j.appender.stdout.layout.ConversionPattern=%d %-5p [%t] %-17c{2} (%13F:%L) %3x - %m%n

    log4j.appender.rolling=org.apache.log4j.DailyRollingFileAppender

    log4j.appender.rolling.File=output.log

    log4j.appender.rolling.Append=true

    log4j.appender.rolling.MaxFileSize=500KB

    log4j.appender.rolling.DatePattern='.'yyyy-MM-dd

    log4j.appender.rolling.layout=org.apache.log4j.PatternLayout

    log4j.appender.rolling.layout.ConversionPattern=%d %-5p [%t] %-17c{2} (%13F:%L) %3x - %m%n


    #최상위 카테고리에 INFO로 레벨 설정 및 appender로 stdout, rolling을 정의

    log4j.rootLogger=INFO, stdout, rolling

    #stdout 어펜더는 콘솔에 뿌리겠다는 정의

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

    #stdout 어펜더는 patternlayout을 사용하겠다는 정의

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

    #페턴은 다음과 같이 포맷팅 하겠다는 것을 정의

    log4j.appender.stdout.layout.ConversionPattern=%d %-5p [%t] %-17c{2} (%13F:%L) %3x - %m%n


    #역시나 rolling 어펜더는 파일로 처리한다라고 정의

    log4j.appender.rolling=org.apache.log4j.DailyRollingFileAppender

    #로그 파일 이름은 output.log

    log4j.appender.rolling.File=output.log

    #true면 톰캣을 내렸다 올려도 파일이 리셋되지 않습니다.

    log4j.appender.rolling.Append=true

    #파일 최대 사이즈는 500KB로 설정

    log4j.appender.rolling.MaxFileSize=500KB

    #파일 포맷은 output.log.2005-03-10 으로 관리하겠다고 정의

    log4j.appender.rolling.DatePattern='.'yyyy-MM-dd

    #역시나 rolling 어펜더는 패턴 레이아웃을 사용하겠다고 정의

    log4j.appender.rolling.layout=org.apache.log4j.PatternLayout

    #rolling 어펜더는 패턴 레이아웃 포맷

    log4j.appender.rolling.layout.ConversionPattern=%d %-5p [%t] %-17c{2} (%13F:%L) %3x - %m%n



    VIII. 설정 포맷


    로그파일명 포맷 (DatePattern)
    로그파일명 포맷입니다. 날짜, 시간 및 분단위로까지 로그 파일을 분리할 수 있습니다.

    형식 설명
    '.'yyyy-MM 매달 첫번째날에 로그파일을 변경합니다
    '.'yyyy-ww 매주의 시작시 로그파일을 변경합니다.
    '.'yyyy-MM-dd 매일 자정에 로그파일을 변경합니다.
    '.'yyyy-MM-dd-a 자정과 정오에 로그파일을 변경합니다.
    '.'yyyy-MM-dd-HH 매 시간의 시작마다 로그파일을 변경합니다.
    '.'yyyy-MM-dd-HH-mm 매분마다 로그파일을 변경합니다.



    PatternLayout 포맷
    로그자체를 어떤 포맷으로 남길지 결정합니다.
    layout에는 HTMLLayout, PatternLayout, SimpleLayout, XMLLayout등이 있으며 PatternLayout이 일반적으로 가장 많이 쓰입니다.


    형식 설명
    %p debug, info, warn, error, fatal 등의 priority 가 출력된다.
    %m 로그내용이 출력됩니다
    %d 로깅 이벤트가 발생한 시간을 기록합니다.
    포맷은 %d{HH:mm:ss, SSS}, %d{yyyy MMM dd HH:mm:ss, SSS}같은 형태로 사용하며 SimpleDateFormat에 따른 포맷팅을 하면 된다
    %t 로그이벤트가 발생된 쓰레드의 이름을 출력합니다.
    %% % 표시를 출력하기 위해 사용한다.
    %n 플랫폼 종속적인 개행문자가 출력된다. \r\n 또는 \n 일것이다.
    %c 카테고리를 표시합니다
    예) 카테고리가 a.b.c 처럼 되어있다면 %c{2}는 b.c가 출력됩니다.
    %C 클래스명을 포시합니다.
    예) 클래스구조가 org.apache.xyz.SomeClass 처럼 되어있다면 %C{2}는 xyz.SomeClass 가 출력됩니다
    %F 로깅이 발생한 프로그램 파일명을 나타냅니다.
    %l 로깅이 발생한 caller의 정보를 나타냅니다
    %L 로깅이 발생한 caller의 라인수를 나타냅니다
    %M 로깅이 발생한 method 이름을 나타냅니다.
    %r 어플리케이션 시작 이후 부터 로깅이 발생한 시점의 시간(milliseconds)
    %x 로깅이 발생한 thread와 관련된 NDC(nested diagnostic context)를 출력합니다.
    %X 로깅이 발생한 thread와 관련된 MDC(mapped diagnostic context)를 출력합니다.

    예시) (같은 색끼리 보시면 됩니다)

    위의 test.jsp를 다음 포맷으로 출력해본다면

    [%c] [%C] [%d] [%F] [%l] [%L] [%m] [%M] [%n] [%p] [%r] [%t] [%x] [%X]는 다음과 같다

    [test.jsp] [org.apache.jsp.test_jsp] [2005-03-10 12:37:23,561] [test_jsp.java] [org.apache.jsp.test_jsp._jspService(test_jsp.java:64)] [64] [fatal!!] [_jspService] [개행] [FATAL] [765567] [http-8080-Processor25] [] []

    posted by 좋은느낌/원철
    2008. 6. 17. 09:25 개발/Java

    [스크랩 원문] http://logging.apache.org/log4j/1.2/manual.html


    Short introduction to log4j: Ceki G?c? March 2002

    Copyright ?2000-2002 The Apache Software Foundation. All rights reserved. This software is published under the terms of the Apache Software License version 2.0, a copy of which has been included in the LICENSE file shipped with the log4j distribution. This document is based on the article "Log4j delivers control over logging" published in November 2000 edition of JavaWorld. However, the present article contains more detailed and up to date information. The present short manual also borrows some text from "The complete log4j manual" by the same author (yours truly).

    Abstract

    This document describes the log4j API, its unique features and design rationale. Log4j is an open source project based on the work of many authors. It allows the developer to control which log statements are output with arbitrary granularity. It is fully configurable at runtime using external configuration files. Best of all, log4j has a gentle learning curve. Beware: judging from user feedback, it is also quite addictive.

    Introduction

    Almost every large application includes its own logging or tracing API. In conformance with this rule, the E.U. SEMPER project decided to write its own tracing API. This was in early 1996. After countless enhancements, several incarnations and much work that API has evolved to become log4j, a popular logging package for Java. The package is distributed under the Apache Software License, a fully-fledged open source license certified by the open source initiative. The latest log4j version, including full-source code, class files and documentation can be found at http://logging.apache.org/log4j/. By the way, log4j has been ported to the C, C++, C#, Perl, Python, Ruby, and Eiffel languages.

    Inserting log statements into code is a low-tech method for debugging it. It may also be the only way because debuggers are not always available or applicable. This is usually the case for multithreaded applications and distributed applications at large.

    Experience indicates that logging was an important component of the development cycle. It offeres several advantages. It provides precise context about a run of the application. Once inserted into the code, the generation of logging output requires no human intervention. Moreover, log output can be saved in persistent medium to be studied at a later time. In addition to its use in the development cycle, a sufficiently rich logging package can also be viewed as an auditing tool.

    As Brian W. Kernighan and Rob Pike put it in their truly excellent book "The Practice of Programming"

      As personal choice, we tend not to use debuggers beyond getting a
      stack trace or the value of a variable or two. One reason is that it
      is easy to get lost in details of complicated data structures and
      control flow; we find stepping through a program less productive
      than thinking harder and adding output statements and self-checking
      code at critical places. Clicking over statements takes longer than
      scanning the output of judiciously-placed displays. It takes less
      time to decide where to put print statements than to single-step to
      the critical section of code, even assuming we know where that
      is. More important, debugging statements stay with the program;
      debugging sessions are transient.
    

    Logging does have its drawbacks. It can slow down an application. If too verbose, it can cause scrolling blindness. To alleviate these concerns, log4j is designed to be reliable, fast and extensible. Since logging is rarely the main focus of an application, the log4j API strives to be simple to understand and to use.

    Loggers, Appenders and Layouts

    Log4j has three main components: loggers, appenders and layouts. These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported.

    Logger hierarchy

    The first and foremost advantage of any logging API over plain System.out.println resides in its ability to disable certain log statements while allowing others to print unhindered. This capability assumes that the logging space, that is, the space of all possible logging statements, is categorized according to some developer-chosen criteria. This observation had previously led us to choose category as the central concept of the package. However, since log4j version 1.2, Logger class has replaced the Category class. For those familiar with earlier versions of log4j, the Logger class can be considered as a mere alias to the Category class.

    Loggers are named entities. Logger names are case-sensitive and they follow the hierarchical naming rule:

    Named Hierarchy
    A logger is said to be an ancestor of another logger if its name followed by a dot is a prefix of the descendant logger name. A logger is said to be a parent of a child logger if there are no ancestors between itself and the descendant logger.

    For example, the logger named "com.foo" is a parent of the logger named "com.foo.Bar". Similarly, "java" is a parent of "java.util" and an ancestor of "java.util.Vector". This naming scheme should be familiar to most developers.

    The root logger resides at the top of the logger hierarchy. It is exceptional in two ways:

    1. it always exists,
    2. it cannot be retrieved by name.
    Invoking the class static Logger.getRootLogger method retrieves it. All other loggers are instantiated and retrieved with the class static Logger.getLogger method. This method takes the name of the desired logger as a parameter. Some of the basic methods in the Logger class are listed below.

      package org.apache.log4j;
    
      public class Logger {
    
        // Creation & retrieval methods:
        public static Logger getRootLogger();
        public static Logger getLogger(String name);
    
        // printing methods:
        public void trace(Object message);
        public void debug(Object message);
        public void info(Object message);
        public void warn(Object message);
        public void error(Object message);
        public void fatal(Object message);
    
        // generic printing method:
        public void log(Level l, Object message);
    }
    

    Loggers may be assigned levels. The set of possible levels, that is:



    TRACE,

    DEBUG,

    INFO,

    WARN,

    ERROR and

    FATAL



    are defined in the org.apache.log4j.Level class. Although we do not encourage you to do so, you may define your own levels by sub-classing the Level class. A perhaps better approach will be explained later on.

    If a given logger is not assigned a level, then it inherits one from its closest ancestor with an assigned level. More formally:

    Level Inheritance

    The inherited level for a given logger C, is equal to the first non-null level in the logger hierarchy, starting at C and proceeding upwards in the hierarchy towards the root logger.

    To ensure that all loggers can eventually inherit a level, the root logger always has an assigned level.

    Below are four tables with various assigned level values and the resulting inherited levels according to the above rule.

    Logger

    name
    Assigned

    level
    Inherited

    level
    root Proot Proot
    X none Proot
    X.Y none Proot
    X.Y.Z none Proot
    Example 1

    In example 1 above, only the root logger is assigned a level. This level value, Proot, is inherited by the other loggers X, X.Y and X.Y.Z.

    Logger

    name
    Assigned

    level
    Inherited

    level
    root Proot Proot
    X Px Px
    X.Y Pxy Pxy
    X.Y.Z Pxyz Pxyz
    Example 2

    In example 2, all loggers have an assigned level value. There is no need for level inheritence.

    Logger

    name
    Assigned

    level
    Inherited

    level
    root Proot Proot
    X Px Px
    X.Y none Px
    X.Y.Z Pxyz Pxyz
    Example 3

    In example 3, the loggers root, X and X.Y.Z are assigned the levels Proot, Px and Pxyz respectively. The logger X.Y inherits its level value from its parent X.

    Logger

    name
    Assigned

    level
    Inherited

    level
    root Proot Proot
    X Px Px
    X.Y none Px
    X.Y.Z none Px
    Example 4

    In example 4, the loggers root and X and are assigned the levels Proot and Px respectively. The loggers X.Y and X.Y.Z inherits their level value from their nearest parent X having an assigned level..

    Logging requests are made by invoking one of the printing methods of a logger instance. These printing methods are debug, info, warn, error, fatal and log.

    By definition, the printing method determines the level of a logging request. For example, if c is a logger instance, then the statement c.info("..") is a logging request of level INFO.

    A logging request is said to be enabled if its level is higher than or equal to the level of its logger. Otherwise, the request is said to be disabled. A logger without an assigned level will inherit one from the hierarchy. This rule is summarized below.

    Basic Selection Rule

    A log request of level p in a logger with (either assigned or inherited, whichever is appropriate) level q, is enabled if p >= q.

    This rule is at the heart of log4j. It assumes that levels are ordered. For the standard levels, we have DEBUG < INFO < WARN < ERROR < FATAL.

    Here is an example of this rule.

       // get a logger instance named "com.foo"
       Logger  logger = Logger.getLogger("com.foo");
    
       // Now set its level. Normally you do not need to set the
       // level of a logger programmatically. This is usually done
       // in configuration files.
       logger.setLevel(Level.INFO);
    
       Logger barlogger = Logger.getLogger("com.foo.Bar");
    
       // This request is enabled, because WARN >= INFO.
       logger.warn("Low fuel level.");
    
       // This request is disabled, because DEBUG < INFO.
       logger.debug("Starting search for nearest gas station.");
    
       // The logger instance barlogger, named "com.foo.Bar",
       // will inherit its level from the logger named
       // "com.foo" Thus, the following request is enabled
       // because INFO >= INFO.
       barlogger.info("Located nearest gas station.");
    
       // This request is disabled, because DEBUG < INFO.
       barlogger.debug("Exiting gas station search");
    

    Calling the getLogger method with the same name will always return a reference to the exact same logger object.

    For example, in

       Logger x = Logger.getLogger("wombat");
       Logger y = Logger.getLogger("wombat");
    x and y refer to exactly the same logger object.

    Thus, it is possible to configure a logger and then to retrieve the same instance somewhere else in the code without passing around references. In fundamental contradiction to biological parenthood, where parents always preceed their children, log4j loggers can be created and configured in any order. In particular, a "parent" logger will find and link to its descendants even if it is instantiated after them.

    Configuration of the log4j environment is typically done at application initialization. The preferred way is by reading a configuration file. This approach will be discussed shortly.

    Log4j makes it easy to name loggers by software component. This can be accomplished by statically instantiating a logger in each class, with the logger name equal to the fully qualified name of the class. This is a useful and straightforward method of defining loggers. As the log output bears the name of the generating logger, this naming strategy makes it easy to identify the origin of a log message. However, this is only one possible, albeit common, strategy for naming loggers. Log4j does not restrict the possible set of loggers. The developer is free to name the loggers as desired.

    Nevertheless, naming loggers after the class where they are located seems to be the best strategy known so far.

    Appenders and Layouts

    The ability to selectively enable or disable logging requests based on their logger is only part of the picture. Log4j allows logging requests to print to multiple destinations. In log4j speak, an output destination is called an appender. Currently, appenders exist for the console, files, GUI components, remote socket servers, JMS, NT Event Loggers, and remote UNIX Syslog daemons. It is also possible to log asynchronously.

    More than one appender can be attached to a logger.

    The addAppender method adds an appender to a given logger. Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy. In other words, appenders are inherited additively from the logger hierarchy. For example, if a console appender is added to the root logger, then all enabled logging requests will at least print on the console. If in addition a file appender is added to a logger, say C, then enabled logging requests for C and C's children will print on a file and on the console. It is possible to override this default behavior so that appender accumulation is no longer additive by setting the additivity flag to false.

    The rules governing appender additivity are summarized below.

    Appender Additivity

    The output of a log statement of logger C will go to all the appenders in C and its ancestors. This is the meaning of the term "appender additivity".

    However, if an ancestor of logger C, say P, has the additivity flag set to false, then C's output will be directed to all the appenders in C and it's ancestors upto and including P but not the appenders in any of the ancestors of P.

    Loggers have their additivity flag set to true by default.

    The table below shows an example:

    Logger

    Name
    Added

    Appenders
    Additivity

    Flag
    Output Targets Comment
    root A1 not applicable A1 The root logger is anonymous but can be accessed with the Logger.getRootLogger() method. There is no default appender attached to root.
    x A-x1, A-x2 true A1, A-x1, A-x2 Appenders of "x" and root.
    x.y none true A1, A-x1, A-x2 Appenders of "x" and root.
    x.y.z A-xyz1 true A1, A-x1, A-x2, A-xyz1 Appenders in "x.y.z", "x" and root.
    security A-sec false A-sec No appender accumulation since the additivity flag is set to false.
    security.access none true A-sec Only appenders of "security" because the additivity flag in "security" is set to false.

    More often than not, users wish to customize not only the output destination but also the output format. This is accomplished by associating a layout with an appender. The layout is responsible for formatting the logging request according to the user's wishes, whereas an appender takes care of sending the formatted output to its destination.

    The PatternLayout, part of the standard log4j distribution, lets the user specify the output format according to conversion patterns similar to the C language printf function.

    For example, the PatternLayout with the conversion pattern "%r [%t] %-5p %c - %m%n" will output something akin to:

    176 [main] INFO  org.foo.Bar - Located nearest gas station.
    

    The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread making the log request. The third field is the level of the log statement. The fourth field is the name of the logger associated with the log request. The text after the '-' is the message of the statement.

    Just as importantly, log4j will render the content of the log message according to user specified criteria. For example, if you frequently need to log Oranges, an object type used in your current project, then you can register an OrangeRenderer that will be invoked whenever an orange needs to be logged.

    Object rendering follows the class hierarchy. For example, assuming oranges are fruits, if you register an FruitRenderer, all fruits including oranges will be rendered by the FruitRenderer, unless of course you registered an orange specific OrangeRenderer.

    Object renderers have to implement the ObjectRenderer interface.

    Configuration

    Inserting log requests into the application code requires a fair amount of planning and effort. Observation shows that approximately 4 percent of code is dedicated to logging. Consequently, even moderately sized applications will have thousands of logging statements embedded within their code. Given their number, it becomes imperative to manage these log statements without the need to modify them manually.

    The log4j environment is fully configurable programmatically. However, it is far more flexible to configure log4j using configuration files. Currently, configuration files can be written in XML or in Java properties (key=value) format.

    Let us give a taste of how this is done with the help of an imaginary application MyApp that uses log4j.

     import com.foo.Bar;
    
     // Import log4j classes.
     import org.apache.log4j.Logger;
     import org.apache.log4j.BasicConfigurator;
    
     public class MyApp {
    
       // Define a static logger variable so that it references the
       // Logger instance named "MyApp".
       static Logger logger = Logger.getLogger(MyApp.class);
    
       public static void main(String[] args) {
    
         // Set up a simple configuration that logs on the console.
         BasicConfigurator.configure();
    
         logger.info("Entering application.");
         Bar bar = new Bar();
         bar.doIt();
         logger.info("Exiting application.");
       }
     }
    

    MyApp begins by importing log4j related classes. It then defines a static logger variable with the name MyApp which happens to be the fully qualified name of the class.

    MyApp uses the Bar class defined in the package com.foo.

     package com.foo;
     import org.apache.log4j.Logger;
    
     public class Bar {
       static Logger logger = Logger.getLogger(Bar.class);
    
       public void doIt() {
         logger.debug("Did it again!");
       }
     }
    

    The invocation of the BasicConfigurator.configure method creates a rather simple log4j setup. This method is hardwired to add to the root logger a ConsoleAppender. The output will be formatted using a PatternLayout set to the pattern "%-4r [%t] %-5p %c %x - %m%n".

    Note that by default, the root logger is assigned to Level.DEBUG.

    The output of MyApp is:

    0    [main] INFO  MyApp  - Entering application.
    36   [main] DEBUG com.foo.Bar  - Did it again!
    51   [main] INFO  MyApp  - Exiting application.
    

    The figure below depicts the object diagram of MyApp after just having called the BasicConfigurator.configure method.

    As a side note, let me mention that in log4j child loggers link only to their existing ancestors. In particular, the logger named com.foo.Bar is linked directly to the root logger, thereby circumventing the unused com or com.foo loggers. This significantly increases performance and reduces log4j's memory footprint.

    The MyApp class configures log4j by invoking BasicConfigurator.configure method. Other classes only need to import the org.apache.log4j.Logger class, retrieve the loggers they wish to use, and log away.

    The previous example always outputs the same log information. Fortunately, it is easy to modify MyApp so that the log output can be controlled at run-time. Here is a slightly modified version.

     import com.foo.Bar;
    
     import org.apache.log4j.Logger;
     import org.apache.log4j.PropertyConfigurator;
    
     public class MyApp {
    
       static Logger logger = Logger.getLogger(MyApp.class.getName());
    
       public static void main(String[] args) {
    
    
         // BasicConfigurator replaced with PropertyConfigurator.
         PropertyConfigurator.configure(args[0]);
    
         logger.info("Entering application.");
         Bar bar = new Bar();
         bar.doIt();
         logger.info("Exiting application.");
       }
     }
    

    This version of MyApp instructs PropertyConfigurator to parse a configuration file and set up logging accordingly.

    Here is a sample configuration file that results in exactly same output as the previous BasicConfigurator based example.

    # Set root logger level to DEBUG and its only appender to A1.
    log4j.rootLogger=DEBUG, A1
    
    # A1 is set to be a ConsoleAppender.
    log4j.appender.A1=org.apache.log4j.ConsoleAppender
    
    # A1 uses PatternLayout.
    log4j.appender.A1.layout=org.apache.log4j.PatternLayout
    log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
    

    Suppose we are no longer interested in seeing the output of any component belonging to the com.foo package. The following configuration file shows one possible way of achieving this.

    log4j.rootLogger=DEBUG, A1
    log4j.appender.A1=org.apache.log4j.ConsoleAppender
    log4j.appender.A1.layout=org.apache.log4j.PatternLayout
    
    # Print the date in ISO 8601 format
    log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
    
    # Print only messages of level WARN or above in the package com.foo.
    log4j.logger.com.foo=WARN
    

    The output of MyApp configured with this file is shown below.

    2000-09-07 14:07:41,508 [main] INFO  MyApp - Entering application.
    2000-09-07 14:07:41,529 [main] INFO  MyApp - Exiting application.
    

    As the logger com.foo.Bar does not have an assigned level, it inherits its level from com.foo, which was set to WARN in the configuration file. The log statement from the Bar.doIt method has the level DEBUG, lower than the logger level WARN. Consequently, doIt() method's log request is suppressed.

    Here is another configuration file that uses multiple appenders.

    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=example.log
    
    log4j.appender.R.MaxFileSize=100KB
    # Keep one backup file
    log4j.appender.R.MaxBackupIndex=1
    
    log4j.appender.R.layout=org.apache.log4j.PatternLayout
    log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
    

    Calling the enhanced MyApp with the this configuration file will output the following on the console.

     INFO [main] (MyApp2.java:12) - Entering application.
    DEBUG [main] (Bar.java:8) - Doing it again!
     INFO [main] (MyApp2.java:15) - Exiting application.
    

    In addition, as the root logger has been allocated a second appender, output will also be directed to the example.log file. This file will be rolled over when it reaches 100KB. When roll-over occurs, the old version of example.log is automatically moved to example.log.1.

    Note that to obtain these different logging behaviors we did not need to recompile code. We could just as easily have logged to a UNIX Syslog daemon, redirected all com.foo output to an NT Event logger, or forwarded logging events to a remote log4j server, which would log according to local server policy, for example by forwarding the log event to a second log4j server.

    Default Initialization Procedure

    The log4j library does not make any assumptions about its environment. In particular, there are no default log4j appenders. Under certain well-defined circumstances however, the static inializer of the Logger class will attempt to automatically configure log4j. The Java language guarantees that the static initializer of a class is called once and only once during the loading of a class into memory. It is important to remember that different classloaders may load distinct copies of the same class. These copies of the same class are considered as totally unrelated by the JVM.

    The default initialization is very useful in environments where the exact entry point to the application depends on the runtime environment. For example, the same application can be used as a stand-alone application, as an applet, or as a servlet under the control of a web-server.

    The exact default initialization algorithm is defined as follows:

    1. Setting the log4j.defaultInitOverride system property to any other value then "false" will cause log4j to skip the default initialization procedure (this procedure).
    2. Set the resource string variable to the value of the log4j.configuration system property. The preferred way to specify the default initialization file is through the log4j.configuration system property. In case the system property log4j.configuration is not defined, then set the string variable resource to its default value "log4j.properties".
    3. Attempt to convert the resource variable to a URL.
    4. If the resource variable cannot be converted to a URL, for example due to a MalformedURLException, then search for the resource from the classpath by calling org.apache.log4j.helpers.Loader.getResource(resource, Logger.class) which returns a URL. Note that the string "log4j.properties" constitutes a malformed URL. See Loader.getResource(java.lang.String) for the list of searched locations.
    5. If no URL could not be found, abort default initialization. Otherwise, configure log4j from the URL. The PropertyConfigurator will be used to parse the URL to configure log4j unless the URL ends with the ".xml" extension, in which case the DOMConfigurator will be used. You can optionaly specify a custom configurator. The value of the log4j.configuratorClass system property is taken as the fully qualified class name of your custom configurator. The custom configurator you specify must implement the Configurator interface.

    Example Configurations

    Default Initialization under Tomcat

    The default log4j initialization is particularly useful in web-server environments. Under Tomcat 3.x and 4.x, you should place the log4j.properties under the WEB-INF/classes directory of your web-applications. Log4j will find the properties file and initialize itself. This is easy to do and it works. You can also choose to set the system property log4j.configuration before starting Tomcat. For Tomcat 3.x The TOMCAT_OPTS environment variable is used to set command line options. For Tomcat 4.0, set the CATALINA_OPTS environment variable instead of TOMCAT_OPTS. Example 1

    The Unix shell command

       export TOMCAT_OPTS="-Dlog4j.configuration=foobar.txt"
    
    tells log4j to use the file foobar.txt as the default configuration file. This file should be place under the WEB-INF/classes directory of your web-application. The file will be read using the PropertyConfigurator. Each web-application will use a different default configuration file because each file is relative to a web-application.

    Example 2

    The Unix shell command

       export TOMCAT_OPTS="-Dlog4j.debug -Dlog4j.configuration=foobar.xml"
    
    tells log4j to output log4j-internal debugging information and to use the file foobar.xml as the default configuration file. This file should be place under the WEB-INF/classes directory of your web-application. Since the file ends with a .xml extension, it will read using the DOMConfigurator. Each web-application will use a different default configuration file because each file is relative to a web-application.

    Example 3

    The Windows shell command

       set TOMCAT_OPTS=-Dlog4j.configuration=foobar.lcf -Dlog4j.configuratorClass=com.foo.BarConfigurator
    
    tells log4j to use the file foobar.lcf as the default configuration file. This file should be place under the WEB-INF/classes directory of your web-application. Due to the definition of the log4j.configuratorClass system property, the file will be read using the com.foo.BarConfigurator custom configurator. Each web-application will use a different default configuration file because each file is relative to a web-application.

    Example 4

    The Windows shell command

       set TOMCAT_OPTS=-Dlog4j.configuration=file:/c:/foobar.lcf
    tells log4j to use the file c:\foobar.lcf as the default configuration file. The configuration file is fully specified by the URL file:/c:/foobar.lcf. Thus, the same configuration file will be used for all web-applications.

    Different web-applications will load the log4j classes through their respective classloaderss. Thus, each image of the log4j environment will act independetly and without any mutual synchronization. For example, FileAppenders defined exactly the same way in multiple web-application configurations will all attempt to write the same file. The results are likely to be less than satisfactory. You must make sure that log4j configurations of different web-applications do not use the same underlying system resource.

    Initialization servlet

    It is also possible to use a special servlet for log4j initialization. Here is an example,

    package com.foo;
    
    import org.apache.log4j.PropertyConfigurator;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.PrintWriter;
    import java.io.IOException;
    
    public class Log4jInit extends HttpServlet {
    
      public
      void init() {
        String prefix =  getServletContext().getRealPath("/");
        String file = getInitParameter("log4j-init-file");
        // if the log4j-init-file is not set, then no point in trying
        if(file != null) {
          PropertyConfigurator.configure(prefix+file);
        }
      }
    
      public
      void doGet(HttpServletRequest req, HttpServletResponse res) {
      }
    }
    

    Define the following servlet in the web.xml file for your web-application.

      <servlet>
        <servlet-name>log4j-init</servlet-name>
        <servlet-class>com.foo.Log4jInit</servlet-class>
    
        <init-param>
          <param-name>log4j-init-file</param-name>
          <param-value>WEB-INF/classes/log4j.lcf</param-value>
        </init-param>
    
        <load-on-startup>1</load-on-startup>
      </servlet>
    

    Writing an initialization servlet is the most flexible way for initializing log4j. There are no constraints on the code you can place in the init() method of the servlet.

    Nested Diagnostic Contexts

    Most real-world systems have to deal with multiple clients simultaneously. In a typical multithreaded implementation of such a system, different threads will handle different clients. Logging is especially well suited to trace and debug complex distributed applications. A common approach to differentiate the logging output of one client from another is to instantiate a new separate logger for each client. This promotes the proliferation of loggers and increases the management overhead of logging.

    A lighter technique is to uniquely stamp each log request initiated from the same client interaction. Neil Harrison described this method in the book "Patterns for Logging Diagnostic Messages," in Pattern Languages of Program Design 3, edited by R. Martin, D. Riehle, and F. Buschmann (Addison-Wesley, 1997).

    To uniquely stamp each request, the user pushes contextual information into the NDC, the abbreviation of Nested Diagnostic Context. The NDC class is shown below.

      public class NDC {
        // Used when printing the diagnostic
        public static String get();
    
        // Remove the top of the context from the NDC.
        public static String pop();
    
        // Add diagnostic context for the current thread.
        public static void push(String message);
    
        // Remove the diagnostic context for this thread.
        public static void remove();
      }
    

    The NDC is managed per thread as a stack of contextual information. Note that all methods of the org.apache.log4j.NDC class are static. Assuming that NDC printing is turned on, every time a log request is made, the appropriate log4j component will include the entire NDC stack for the current thread in the log output. This is done without the intervention of the user, who is responsible only for placing the correct information in the NDC by using the push and pop methods at a few well-defined points in the code. In contrast, the per-client logger approach commands extensive changes in the code.

    To illustrate this point, let us take the example of a servlet delivering content to numerous clients. The servlet can build the NDC at the very beginning of the request before executing other code. The contextual information can be the client's host name and other information inherent to the request, typically information contained in cookies. Hence, even if the servlet is serving multiple clients simultaneously, the logs initiated by the same code, i.e. belonging to the same logger, can still be distinguished because each client request will have a different NDC stack. Contrast this with the complexity of passing a freshly instantiated logger to all code exercised during the client's request.

    Nevertheless, some sophisticated applications, such as virtual hosting web servers, must log differently depending on the virtual host context and also depending on the software component issuing the request. Recent log4j releases support multiple hierarchy trees. This enhancement allows each virtual host to possess its own copy of the logger hierarchy.

    Performance

    One of the often-cited arguments against logging is its computational cost. This is a legitimate concern as even moderately sized applications can generate thousands of log requests. Much effort was spent measuring and tweaking logging performance. Log4j claims to be fast and flexible: speed first, flexibility second.

    The user should be aware of the following performance issues.

    1. Logging performance when logging is turned off.

      When logging is turned off entirely or just for a set of levels, the cost of a log request consists of a method invocation plus an integer comparison. On a 233 MHz Pentium II machine this cost is typically in the 5 to 50 nanosecond range.

      However, The method invocation involves the "hidden" cost of parameter construction.

      For example, for some logger cat, writing,

           logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
          
      incurs the cost of constructing the message parameter, i.e. converting both integer i and entry[i] to a String, and concatenating intermediate strings, regardless of whether the message will be logged or not. This cost of parameter construction can be quite high and it depends on the size of the parameters involved.

      To avoid the parameter construction cost write:

            if(logger.isDebugEnabled() {
              logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
            }
         

      This will not incur the cost of parameter construction if debugging is disabled. On the other hand, if the logger is debug-enabled, it will incur twice the cost of evaluating whether the logger is enabled or not: once in debugEnabled and once in debug. This is an insignificant overhead because evaluating a logger takes about 1% of the time it takes to actually log.

      In log4j, logging requests are made to instances of the Logger class. Logger is a class and not an interface. This measurably reduces the cost of method invocation at the cost of some flexibility.

      Certain users resort to preprocessing or compile-time techniques to compile out all log statements. This leads to perfect performance efficiency with respect to logging. However, since the resulting application binary does not contain any log statements, logging cannot be turned on for that binary. In my opinion this is a disproportionate price to pay in exchange for a small performance gain.

    2. The performance of deciding whether to log or not to log when logging is turned on.

      This is essentially the performance of walking the logger hierarchy. When logging is turned on, log4j still needs to compare the level of the log request with the level of the request logger. However, loggers may not have an assigned level; they can inherit them from the logger hierarchy. Thus, before inheriting a level, the logger may need to search its ancestors.

      There has been a serious effort to make this hierarchy walk to be as fast as possible. For example, child loggers link only to their existing ancestors. In the BasicConfigurator example shown earlier, the logger named com.foo.Bar is linked directly to the root logger, thereby circumventing the nonexistent com or com.foo loggers. This significantly improves the speed of the walk, especially in "sparse" hierarchies.

      The typical cost of walking the hierarchy is typically 3 times slower than when logging is turned off entirely.

    3. Actually outputting log messages

      This is the cost of formatting the log output and sending it to its target destination. Here again, a serious effort was made to make layouts (formatters) perform as quickly as possible. The same is true for appenders. The typical cost of actually logging is about 100 to 300 microseconds. See org.apache.log4.performance.Logging for actual figures.

    Although log4j has many features, its first design goal was speed. Some log4j components have been rewritten many times to improve performance. Nevertheless, contributors frequently come up with new optimizations. You should be pleased to know that when configured with the SimpleLayout performance tests have shown log4j to log as quickly as System.out.println.

    Conclusions

    Log4j is a popular logging package written in Java. One of its distinctive features is the notion of inheritance in loggers. Using a logger hierarchy it is possible to control which log statements are output at arbitrary granularity. This helps reduce the volume of logged output and minimize the cost of logging.

    One of the advantages of the log4j API is its manageability. Once the log statements have been inserted into the code, they can be controlled with configuration files. They can be selectively enabled or disabled, and sent to different and multiple output targets in user-chosen formats. The log4j package is designed so that log statements can remain in shipped code without incurring a heavy performance cost.

    Acknowledgments

    Many thanks to N. Asokan for reviewing the article. He is also one of the originators of the logger concept. I am indebted to Nelson Minar for encouraging me to write this article. He has also made many useful suggestions and corrections to this article. Log4j is the result of a collective effort. My special thanks go to all the authors who have contributed to the project. Without exception, the best features in the package have all originated in the user community.
    posted by 좋은느낌/원철
    2008. 6. 17. 09:20 개발/Java

    Ant

    스크랩 원본 : http://www.javastudy.co.kr/docs/lec_oop/ant/ant1.htm

    ANT (상): Ant 무엇에 쓰는 물건인고?

    저자: 김영익

    자바 빌드 도구인 Ant와 이를 이용한 실전예제를 다루는 기사이다. Ant는 실제로 어떤 프로그램을 개발하느냐에 상관없이 사용되는 빌드 도구로 얼마나 개발을 편리하게 해주느냐가 관건이지 프로그램이나 프로젝트와는 특별한 관계가 없다. 본 기사는 모든 자바 개발자를 대상으로하여 작성되었다. 초급자에게는 앞으로 진행할 프고젝트나 프로그램을 편하게 개발할 수 있게 해주며, 중급 이상자에게는 더욱 더 게을러질 수 있는(?) 기회를 제공해 줄 것이다.

    1. Ant 개요

    다음은 Ant를 소개하는 자카르타 사이트의 원문 중에서 처음 부분이다.
    Apache Ant is a Java based build tool. In theory it is kind of like make without make's wrinkles. Why another build tool when there is already make, gnumake, nmake, jam, and others? Because all of those tools have limitations that Ant's original author couldn't live with when developing software across multiple platforms. . . . 이후 생략(http://jakarta.apache.org/ant/index.html 참고).
    Ant가 탄생하게 된 배경을 원문과 필자의 경험으로 간추려 보면 다음과 같다.
    C나 C++를 사용하는 개발자들은 대부분 make나 nmake 또는 기타 다른 빌드 도구를 사용해왔다. 그렇다면 자바 개발자들은 어떤 빌드 도구를 사용할 것인가? 물론 make를 사용할 수 있다. 실제로 필자도 본인과 절친한 개발자가 만든 make 파일을 사용한 적이 있었다. 하지만 근본적으로 자바 언어를 위한 것이 아니기 때문에 불편하고 심지어는 필요한 기능이 없을 수도 있다. 하지만 이제는 걱정할 필요가 없다. 우리에겐 Ant가 있기 때문이다. Ant는 make를 비롯한 기존의 빌드 도구를 사용하면서 겪게 되는 많은 어려움을 줄여주면서 더 많은 기능을 제공한다. 물론 처음 배우는 개발자들에겐 약간의 시간을 투자해야 하는 부담이 가겠지만 일단 배우고 나면 그 효과는 투자한 시간에 비해 몇 배 이상이 될 것이다.
    Ant와 같은 빌드 도구를 사용하지 않을 경우 도스 창에서 클래스 패스에 클래스를 추가하거나 소스 파일 컴파일, jar 파일로 묶는 작업, 묶은 jar 파일을 특정 디렉토리로 이동시키고 수정된 내용을 javadoc으로 문서화 시키는 등의 작업은 소스가 수정될 때마다 한 단계씩 도스 창에서 모두 입력해야 한다. 하지만 Ant를 사용하면 마치 배치(bat) 파일을 실행한 것처럼 이와 같은 일련의 작업들을 Ant를 이용하여 단 한번에 수행할 수 있다. 정말 편리하지 않겠는가?

    Ant의 주요 기능을 알기 쉽게 몇 가지만 나열해 보면 아래와 같다.
    • 자바 소스 파일 컴파일(너무 당연하다)
    • jar, war, ear, zip 파일의 생성
    • javadoc을 실행하여 도움말 생성
    • 파일이나 폴더의 이동 및 복사, 삭제
    • 각각의 작업에 대한 의존성 설정
    • 유닉스에서처럼 파일이나 폴더에 퍼미션 설정
    • 파일의 변경 날짜를 설정하는 touch 기능
    • 외부 프로그램의 실행
    이외에도 너무 많아서 나열할 수 가 없을 정도로 많은 기능들이 있다. 하지만 뭐니 뭐니 해도 가장 유용한 기능은 빌드할 때마다 수많은 키보드를 두드려야 하는 단순 노동을 하지 않아도 된다는 것이고 플랫폼에 무관한 XML을 이용한다는 것이다. XML을 사용하는 것이 무슨 장점이 될 수 있냐고 하실 분들도 있을지 모르겠다. 하지만 예전에 make 파일을 사용하면서 특정 부분에서 항상 앞에 탭(tab)키를 입력해야만 하는 것을 몰라서 개발자들이 고생하는 것을 본 적이 있다. Ant의 등장은 이와 같은 모호함을 없애자는 것이다. 또한 XML은 이미 IT 업계의 상당 부분에서 표준으로 자리를 잡아 가고 있는 현실이다. 냉혹한 현실에 뒤쳐지는 개발자는 살아 남을 수 없다.

    2. 어디에서 Ant를 구할 수 있나?

    Ant는 Jakarta 사이트에 가면 다운 받을 수 있다. 어서 가서 받아 두자.
    http://jakarta.apache.org/builds/ant/release/v1.4.1/bin/

    이 글을 쓰는 시점에서는 버전 1.4.1이 가장 최신의 버전이지만 Ant도 버전에 따라 API의 변화가 있다. 버전이 다르면 빌드할 때 'deprecated …'와 같은 메시지가 뜨거나 에러가 발생할 수 있으므로 가능한 한 같은 버전을 다운 받아서 사용하길 권장하는 바이다.

    3. Ant 설치

    설치에는 그다지 복잡한 사항이 없다. 일단 사이트에서 다운로드 받은 압축 파일(jakarta-ant-1.4.1-bin.zip)을 적당한 위치에 풀어놓기만 하면 된다. 그리고 몇 가지 환경 설정을 추가로 해줄 필요가 있다.

    설치한 폴더가 c:\dev\tools\jakarta-ant-1.4.1 일 경우 [그림 1]처럼 디렉토리와 파일들이 생성된다.

    /bin : Ant 실행을 위한 배치 파일이 있다(유닉스나 리눅스의 경우 셸 파일 사용)
    /lib : jar 파일들
    /docs : 매뉴얼과 API 문서가 있다.


    [그림 1] 설치 후 디렉토리 및 파일

    윈도우 환경에서는 환경 설정을 다음과 같이 해주면 된다.
    set ANT_HOME=c:\dev\tools\jakarta-ant-1.4.1
    set JAVA_HOME=c:\jdk1.3.1
    set PATH=%PATH%;%ANT_HOME%\bin
    
    유닉스나 기타 다른 운영체제에서의 설정은 Ant 매뉴얼(http://jakarta.apache.org/ant/manual/install.html)을 참고하기 바란다.

    4. Hello Ant !

    이제 설치가 끝났으니 실전 예제로 들어가 보도록 하자. 개발자들에게는 이미 익숙한 Hello 예제부터 시작할 것이다.

    4.1 준비하기

    먼저 적절한 폴더 설정과 소스 파일이 당연히 필요하다. 그림과 같이 c:\\ant_test 폴더를 만들고 하위 폴더로 classes, doc, jar, src 폴더를 생성한다. 그리고 src 폴더 밑에는 HelloAnt.java 파일을 하나 생성한다.


    [그림 2] HelloAnt.java 파일을 만든다

    HelloAnt.java의 내용은 어떤 것이라도 상관 없으니 여러분께서 알아서 하시길...

    4.2 Build.xml

    Ant를 실행하면 초기값으로 현재 폴더에 있는 build.xml 파일을 찾아서 빌드하게 된다. 여기에서는 build.xml 파일의 위치를 "C:\ant_test" 밑에 두었다.


    [그림 3] build.xml 생성

    이제부터는 build.xml 파일을 살펴볼 것이다. 혹시 XML에 익숙치 않다고 하더라도 겁먹지 말고 차근차근 살펴보도록 하자. 만약 아래의 XML 파일을 사용할 때는 반드시 주석문을 제거하고 사용해야 한다. 그렇지 않으면 Ant를 실행할 때 에러가 발생한다.
    <?xml version="1.0"?>
    
    <!--
    name : 프로젝트 이름
    default : 초기치로 설정되는 작업, 아무 것도 지정하지 않고 실행하면 이 작업을 수행
    basedir : 프로젝트에 대한 기준 폴더를 지정
    property : 프로젝트에서 사용할 각 폴더들의 위치를 지정
    ${basedir} : 이미 앞에서 설정된 값을 읽어온다
    -->
    
    <project name="HelloAnt" default="javadoc" basedir="." >
    <property name="src.dir" value="${basedir}/src" />
    <property name="classes.dir" value="${basedir}/classes" />
    <property name="jar.dir" value="${basedir}/jar" />
    <property name="javadoc.dir" value="${basedir}/doc" />
    
    
    <!--
    target : 각각의 타겟을 지정, 타겟이란 프로젝트를 이루는 하나 하나의 작업 단위
    srcdir : 컴파일 하기 위한 자바 소스 파일의 위치를 지정
    destdir : 어느 폴더에 클래스 파일들을 위치 시킬지 지정
    -->
    
    <target name="compile" >
    <javac srcdir="${src.dir}" destdir="${classes.dir}" />
    </target>
    
    <!--
    jar : 파일을 만든다
    depends : compile 정상적으로 수행되어야만 진행
    jarfile : jar 파일의 위치와 파일 이름 지정
    basedir : jar로 묶을 클래스 파일의 위치
    includes : 모든 폴더에서 클래스 파일들만 포함
    -->
    
    <target name="jar" depends="compile">
    <jar jarfile="${jar.dir}/hello.jar"
    basedir="${classes.dir}"
    includes="**/*.class"
    />
    </target>
    
    <!--
    javadoc을 실행
    depends : compile과 jar 수행이 정상적으로 끝나야만 실행
    sourcepath : 소스 폴더 지정
    sourcefiles : 소스 파일 지정
    windowtitle : 제목 지정
    destdir : 파일 생성후 저장할 폴더 지정
    -->
    
    <target name="javadoc" depends="compile, jar" >
    <javadoc
    sourcepath="${src.dir}"
    sourcefiles="${src.dir}/HelloAnt.java"
    windowtitle="HelloAnt API"
    destdir="${javadoc.dir}"
    />
    </target>
    
    <!--
    소스 코드를 제외한 모든 작업 파일들과 폴더를 삭제한다
    -->
    
    <target name="clean" >
    <delete dir="${classes.dir}/classes/*"/>
    <delete dir="${jar.dir}/jar/*"/>
    <delete dir="${javadoc.dir}/doc/*"/>
    </target>
    
    </project>
    
    이런 파일을 한번만 만들어 두면 다른 프로젝트를 할 때도 조금씩 수정해서 계속 써먹을 수 있다. 재사용(reuse)이란 그래서 좋은 것이다.

    4.3 Ant 실행

    그럼 어떻게 실행하면 될까? 먼저 실행할 때 필요한 옵션으로는 어떤 것들이 있는지 알아보자. 도스 창 프롬프트에서 'ant ?help' 라고 입력한다
    C:\ant_test>ant -help
    ant [options] [target [target2 [target3] ...]]
    Options :
      -help                   도움말을 보여준다.
      -projecthelp            프로젝트에 필요한 도움을 보여준다
      -version                현재 ant 버전을 보여준다
      -quiet                  build하는 과정을 디스플레이 하지 않는다.
      -verbose                verbose모드를 실시한다.
      -debug                  debugging 정보를 보여준다.
      -emacs                  로깅 정보를 만들어낸다
      -logfile file           주어진 파일로 로그를 출력한다.
      -logger classname       클래스를 이용하여 로깅을 수행한다.
      -listener classname     리스너클래스를 추가한다.
      -buildfile file         대상 build파일을 정의한다.
      -D<property>=<value>    build설정에 필요한 프로퍼티를 사용한다.
      -find file              루트로부터 buildfile을 찾아서 실행한다.
    
    앞에서 만든 빌드 파일을 실행한 결과는 다음과 같다. 실행은 build.xml 파일이 있는 폴더에서 도스 창을 열고 'ant'라고만 입력하면 된다.
    C:\ant_test>ant
    Buildfile: build.xml
    
    compile:
    
    jar:
    
    javadoc:
      [javadoc] Generating Javadoc
      [javadoc] Javadoc execution
      [javadoc] Loading source file C:\ant_test\src\HelloAnt.java...
      [javadoc] Constructing Javadoc information...
      [javadoc] Building tree for all the packages and classes...
      [javadoc] Building index for all the packages and classes...
      [javadoc] Building index for all classes...
    
    BUILD SUCCESSFUL
    
    Total time: 3 seconds
    C:\ant_test>
    
    폴더를 살펴보면 각 폴더에 클래스 파일들, jar 파일, HTML 문서가 생성된 것을 확인할 수 있다. 만일 Ant를 실행할 때 에러가 발생했다면 왜 에러가 발생하는 것인가? 앞에서 필자는 주석문을 제거하고 사용하기를 권고했다. 주석문을 제거하지 않고 사용할 경우 다음과 같은 에러 메시지를 출력하면서 Ant는 실패 결과를 알려준다.
    C:\ant_test>ant
    Buildfile: build.xml
    
    BUILD FAILED
    
    C:\ant_test\build.xml:1: Character conversion error: "Malformed UTF-8 char -- is
     an XML encoding declaration missing?" (line number may be too low).
    
    Total time: 0 seconds
    C:\ant_test>
    
    위와 같이 에러가 발생했을 경우 메시지를 보면서 하나씩 해결해 나가도록 하자. 그리고 그 해결은 여러분 스스로 해보길 바란다.

    다음 기사에서는 Ant 실전 예제를 비록하여 Jbuilder에서 AntRunner 사용하기에 대해 살펴볼 것이다.
    posted by 좋은느낌/원철
    2008. 6. 16. 19:13 일상
    액정이 나갔다..

    돈도 나갔다..

    아...약하디 약한 그 이름 액정이여...

    산산히 부서진 액정이여...

    다시 오지 못할 곳으로 가버린 액정이여..

    남은 자에게 아픔과 경제적 부담만 주고 떠나간 액정이여...



    어쨌든 회사에 청구할 수는 있으니 언젠가는 결재가 되겠지..

    posted by 좋은느낌/원철
    2008. 6. 14. 23:35 일상/교회

    침례교도들의 주된 관심이 세례(침례)식에 관한 것이라고 생각하는 것은 그들에 대한 일반적인 오해이다. 침례교도들의 확신은 근본적으로 교회의 영성에 근거되어 있으며 신자들에 대한 세례(침례)는 오직 이에 대한 추론에 따라, 그리고 신약의 가르침에 의거하여 시행된다. 침례교도들이 취하는 신학적인 견해는 다음과 같이 제시될 수 있다.

    Ⅰ. 교회의 구성원
    침례교도들의 신앙에 따르면 교회는 성령에 의해 거듭나고, 주 예수 그리스도에 대한 개인적이며 구원하는 믿음을 가진 자들로 구성된다. 그러므로 그리스도와의 살아있고 직접적인 앎은 교회 구성원에 있어 기본적인 것으로 주장된다. 이러한 주장은 소극적인 의미에서, 교회를 국가와 동일시하는 사상에 대한 거부를 함축하고 있다. 기독교 교회의 구성원이 되는 것은 출생이라고 하는 우연적인 사건이나 특혜에 근거되어 있지 않으며, 기독교 국가나 기독교 가정에 근거되어 있지도 않다. 그러므로 침례교도들은 "그들의 자녀들과 함께"란 구절을 삭제하여 자체 교회의 정의를 내림으로써 영국 국교와 장로교회의 견해를 거부한다. 교회 구성원에 대한 이러한 견해는 적극적인 의미에서, 교회는 자의적으로 입교된다는 것과, 오직 신자만이 세례(침례)식에 참여한다는 것을 가리킨다. 비록 모든 교회 구성원이 은사에 있어서는 각각 다르지만 신분에 있어서는 모두가 동일하다.

    Ⅱ. 교회의 성격
    침례교도들의 확산은 일종의 제도적이거나 지역적인 교회 개념을 주장하지 않고'회집 교회' 개념을 주장한다. 교회 구성원들은 하나님에 의해서 그리스도의 주권 하에 생명과 봉사의 친교로 결속된다. 그들은 하나님의 법에 따라 함께 살 뿐 아니라, 성령에 의해 조성되고 유지되는 친교를 맺을 것을 약속한다. 이러한 의미의 교회는 자체의 지교회에서 가장 명백하게 인식된다. 따라서 비록 가견적인 교회가 하늘과 땅에 있는, 과거, 현재와 미래의 모든 구속받은 자들로 구성되긴 하지만 또한 신자들이 복음에 의한 친교로, 그리스도의 주권 하에서 함께 살고 있는 곳은 어디에나 교회가 존재한다고 참으로 말할 수 있다.

    Ⅲ. 교회 정치
    그리스도가 교회의 유일한 머리이실 뿐 아니라 최초의 침례교도들은 자신들이, "구속자의 면류관"이라 부르던 것을 진심으로 옹호하였다. 지교회는 자치적이며 그 정치 원리는 종종 "교회들의 회중 질서"로 묘사된다. 침례교도들은 자체의 업무들을 처리할 지방 교회의 능력을 믿을 뿐 아니라, 교회 정치의 상관적인 제도들(감독제, 장로회제, 감리교파)에 대조되는 지교회의 신학적인 중요성 때문에 자체의 명칭을 "침례 교회"(the Baptist Church)라 말하지 않고 일정한 지역에 있는 "침례 교회들"(the Baptist Churcher)이라 부른다. 교회들의 회중 질서, 곧 교회 정치는 지방 회중의 생각에 따라, 민주정체에 대한 인본주의적인 개념과 동등시 되어서는 안된다. 그것을 민주정체란 말로 표현하기란 너무나 졸렬하고 빈약하기 때문이다. 침례교도는 교회가 목사들의 명령이나 보다 높은, 혹은 상회 조직 하의 재판부에 의해서가 아니라 각 지교회 성원들의 마음에서 성령의 음성을 통하여 치리되어야만 한다고 믿는다. 엄격한 의미의 민주적 교회 정치에 있어서는 교회가 교회에 의해서 통치 되어야 하듯이, 침례교도들의 입장은 교회를 통한 교회 정치를 교회에 대한 그리스도의 통치로 인정한다. 모든 교회 성원의 신분의 동등함과 은사의 다양성에 대한 인정에서 다음과 같은 두 가지 사실을 말할 수 있다. 첫째, 각 성원은 지교회의 정치에 있어 권리와 의무를 갖고 있다는 것과 둘째, 교회는 선택된 지도자들의 지도를 기꺼이 받아 들인다는 것이 인정된다. 침례 교회는 보통 자체의 정치에 있어 독자적인 것으로 간주되지만 그러나 그들은 자신들을 위해 독자성을 자랑하지 않는다. 침례교도들은 언제나 교회들간의 제휴의 위대한 가치를 인정해 왔으며, 침례 교회들의 제휴는 수세기 동안 챔례교도들의 생활의 특징이 되어 왔다. 그러나 그러한 모든 제휴는 자의적이며, 침례 교도의 연합 혹은 침례교도의 세계 연맹이 침례교도의 공동체와 동시적인 것이라고 가정하는 오해를 범해서는 안된다.

    Ⅳ. 교회의 의식
    교회 의식을 셋으로 말하여 설교를 포함 시키는 것이 더 적절할지도 모르지만 교회의식은 보통 두 가지, 곧 신자의 세례(침례)와 성찬으로 언급된다. 침례교도들은, 성례란 말이 그 자체에 집중시켜 온 어떤 성직 개념들 때문에 성례보다는 의식이란 말을 사용하기를 좋아하였다. 의식이란 말은 그 자체 배후에 있는, 그리스도께서 정하신 권위를 가리킨다. 침례교도들은 성찬 예식을 쯔빙글리의 견해에 따라 집행한다. 빵과 포도주는 하나님께서 주시는 주의 구원하는 은혜에 대한 증거이다. "그러나 그러한 의식의 가치는 실제의 빵과 포도주 자체보다는 훨씬 더 그것들의 상징에 있다"(Dunkin), 헨리 쿼(Henry Cook)은 다음과 같이 쓴다. "그것들(세례(침례)와 성찬식)은 복음의 핵심을 구성한다는 사실을 상징함으로써 신자의 마음 속에, 하나님은 그의 은혜와 능력의 활력을 부여하고 풍성하게 하는 경험을 통하여 자신을 성령에 의해 전달할 수 있다는, 경외와 사랑과 기도의 감정을 불러 일으킨다". 침례교도들은 세례(침례)와 성찬식이 은혜의 방법이며 복음에 대한 설교 역시 그러한 방법이라는 것을 인정한다. 이러한 견해는, 그러한 의식이 은혜의 특별한 방법일 분 특별 은혜의 방법은 아니란 말로 요약되어 왔다. 신자의 세례(침례)와 성찬식은 교회 의식들이라는 것, 곧 그것들은 개인적인 행위보다는 회중의 행위라는 것이 이러한 주제에 대한 침례교도들의 견해의 일부이기도 하다. 침례교도들은 성직자들의 중재를 몹시 싫어할 뿐 아니라 그들에게 있어 그러한 중재는 유일한 대제사장이신 그리스도의 영광을 손상시키는 것이다. 신자의 세례(침례)에 대한 상세하게 논한 기사를 위해서는 '신자의 세례(침례)' 항목을 보라.

    Ⅴ. 교회의 직무
    교회의 직무는 교회의 친교만큼이나 광범위하지만 그러나 교회 직무란 말은 지도력을 목적으로, 감독과 제도상의 의무를 갖고 있는 자들에게 적용되어 왔다. 침례교도들은 사제적인 계급 의식에서 성직을 믿지 않는다. 침례교의 목사는 목사가 아닌 사람보다 은혜를 '더'받지 않는다. 그는 자신의 공적인 직무에 의해 교회의 가장 작은 회원보다 하나님께 더 가까이 서지 못한다. 그러나 은사는 다양할 뿐 아니라 섬김의 은사는 바울 자신이 에베소서 3:8에서 암시했듯이, 하나님의 은혜에 의한 것으로 인정된다. 비록 목사와 집사가 자주 침례교회의 보다 넓은 친교 관계에서 임명되긴 하지만, 그들은 지교회에 의해 뽑혀 임명된다. 침례교 목사는 하나님의 내적인 부름에 의해 임명되는데 그러한 부름은 교회의 외적인 부름에서 확신을 얻는다. 이러한 하나님의 부르심에 대한 공적인 인정은 성직 수임식에서 받게 되는데 그러한 수임식이 어떤 보다 우수하거나 성직자적인 은혜를 베푸는 것이 아니라 그것은 단지 교회 자체 내에서의 섬김을 인정하고 질서있게 할 뿐이다. 성직 수임식의 중요성은 교회 자체가 목사를 통하여 설교한다는 사실에 있다. 그리고 비록 성직 수임식이 성령의 활동을 교회법적으로 임명된 설교자들의 한계 내로 제한시키려고 의도된것은 아니지만, 그럼에도 불구하고 교회의 이름으로 말해야만 하는 자들의 합당한 위임에 주목할 만한 중요성이 있다.

    Ⅵ. 교회의 보편성
    1920년 램버스 회의(the Lambeth Conference)에 의해 발행된 "모든 기독교 신자들에 대한 호소"(Appeal to all Christian Believers)가 침례교회에 의해 경건문으로 인정되었다. 이 교회들은 1926년에 다른 교파들에 관하여 침례교도들의 견해가 솔직하게 상술되었던 방식으로 한 응답서를 출간하였다. 그 해 리드스(Leeds)에서 침례교도 연합 총회에 의해 채택된 이 응답서에는 다음과 같은 대목들이 내포되어 있다. "우리는 우리 주시요 구주이신 예수 그리스도를 따르고 섬기는 모든 사람들 중 보다 큰 화합에 대한 갈망과 기도로 영국의 형제들과 연합한다...". "우리는 믿음과 행위에 관한 모든 문제에 있어 유일하시고 절대적인 권위로서, 성경에 계시된 우리의 하나님이시요, 구주이신 주예수 그리스도를 경외하고 복종할 뿐 아니라, 각 교회는 그의 말씀을 해석하고 전할 자유를 갖고 있음을 우리는 주장한다. 우리는 다른 견해를 취하는 자들의 양심을 심판하지 않으나, 우리는 그리스도 하에서 각 교회의 자유의 이러한 원리가 성경의 인가와 역사적인 정당성을 갖고 있다는 것을 믿으며, 그러므로 우리는 우리가 신뢰할 수 없는것이 아닌 한 이러한 원리를 저버릴 수 없다. 더우기 우리 주의 주권과 유일한 권위는 그의 교회 안에서 자체의 자유를 해칠지도 모를 국가와의 어떤 관계를 제외시킨다는 것은 명백하다". "교회에 대한 이러한 견해는 램버스 호소(Lambeth Appeal)에 의해 야기된 특별한 문제들에 대한 우리의 태도를 결정한다...". "우리가 교회는 기독교 신자들의 공동체라고 주장하기 때문에 세례(침례)는 우리 중 오직 회개와 믿음에 대해 개인적인 고백을 하는자들에게만 베풀어진다...개인적인 신앙 고백을 할 수 없는 유아들에 대한 세례(침례)가 우리의 판단으로는 기독교 신자들의 친교로써의 교회의 개념을 전복시킨다...". "우리들 교회는 성찬식을 정규적이고 헌신적으로 준수한다. 우리에게 있어 성찬식의 가치는 우리 주의 임재와, 우리가 그의 구속적인 희생을 명시하는 빵과 포도주를 받아 들이는 믿음에 있으며, 성찬식 집행자의 공적인 지위나 봉헌의 말로 인한 빵과 포도주에 있어서의 어떤 변화에 있지 않다. 은혜의 방편으로서의 주의 성만찬의 완전한 효력이 감독 제도의 의식에 달려 있다고 주장하는 것은 그것이 그리스도 안에 있다는 명백성에 모순되는 것처럼 보인다".

    posted by 좋은느낌/원철
    2008. 6. 13. 21:35 카테고리 없음

    네이버 블로그를 한참 쓰다가 네이버의 하는 꼬라지를 보고 옮겨볼까 해서 티스토리를 찾아왔습니다..

    다행이 같이 프로젝트 진행하는 분이 초대장이 있어서 쉽게(?) 들어왔네요..

    이제부터 시작입니다..

    필요한 부분들을 차근차근 모아볼 예정입니다..



    다들 화이팅입니다..



    근데 아직도 퇴근 안 하는 이분들은 도대체 뭡니까?

    posted by 좋은느낌/원철