log4j.properties 설정법...


로그4J 라이브러리 임포트 과정은 생략함니다.

로그4J가 import된 프로젝트의 Src 폴더에 아래와같은 파일을 생성함니다

log4j.properties

이제 log4j가 업무를 수행할때 해당 파일에 들어있는 환경변수들을 사용하여 출력 함니다.

log4j.properties 파일 내부데이터로 들어가겠습니다.

먼저 출력 객체의 선언 임니다.

두가지 객체 선언 방법이 있습니다.
log4j.rootLogger       
log4j.logger.

전자의 경우 rootLogger로서 해당 프로젝트내에서 발생하는 로그업무를 모두 출력 합니다.
(레벨별 제한은 물론 함니다.)

후자의 경우 logger 뒤에 '.' 가 있는데. 해당 프로젝트내의 특정 패키지를 계속 이어붙임니다.
ex) log4j.logger.baeseulki.seul

이렇게하면 저 패키지에서 일어나는 로그업무에 대해서만 처리함니다.

객체선언의 마지막 할당 입니다.

log4j.rootLogger               =     debug, hoho, haha
log4j.logger.baeseulki.seul      =      info, seul, kikiki

오른쪽에 1번째 변수는 출력해줄 경보레벨의 제한임니다.
info의 경우 debug.info.warn.err.fatal 에서 debug는 출력되지 않습니다.

2번째 이상부터는 객체 명임니다. 아래에서 객체명을 통해서 로그의 출력방법, 출력 형식등을 설정함니다.

즉 현재 루트로거에는 hoho와 haha방식으로 출력한다고 보면 되겠습니다.

두방법 다 사용하면
두방법다 객체에 지정한 방법대로 출력함니다. 이제 출력 객체 설정에 들어감니다.


출력 객체로의 접근방법은 다음과 같습니다.

log4j.appender.객체명.객체의 속성값 = 속성에 적용할 값

객체명은 hoho , seul, 과 같이 우리가 생성한 객체입니다.
속성값은 file 같이 정해진 특정 속성입니다.
file 속성은 출력할 파일명을 말함니다.
ex) log4j.appender.hoho.file = c/log/hoho.log

일단 객체의 출력 방법부터 설정합시다. 출력 방법의 경우 속성값이 없습니다. 객체 자체에 넣습니다.

og4j.appender.객체명 = 출력방식

출력방식은 정해진 값들이 있습니다.
org.apache.log4j.ConsoleAppender     //콘솔창에 출력
org.apache.log4j.DailyRollingFileAppender       //파일에 출력

ex)  log4j.appender.hoho = org.apache.log4j.DailyRollingFileAppender


layout 속성은 출력한 스타일을 표현함니다. 2중으로 사용함니다.
일반적인 PatternLayout을 사용함니다.

세부적인 내용은  layout.ConversionPattern 에 추가로 설정합니다.
아래와같이 함니다.

log4j.appender.hoho.layout=org.apache.log4j.PatternLayout
log4j.appender.hoho.layout.ConversionPattern=[%d] %-5p %l - %m%n

아래 패턴에 들어가는 내용은 프로그램상에서
private static Logger logger = Logger.getLogger(seul.class);
logger.debug("슬슬");

여기 들어간 슬슬 이라는 출력 내용을 ConversionPattern 의 형태로 변경하여 출력 함니다.
Pattern의 %? 값들의 내용은 다음과 같습니다.

%p : 호출명(ex DEBUG, INFO, WARN, ERROR, FATAL)
%n : 줄바꿈
%m : 매개변수 메세지
%t : 스레드
%F : 실행파일명
%M : 수행 메소드
%L : 라인????넘버
%d : 날짜


log4j.appender.hoho.DatePattern='.'yyyy-MM-dd
// 매일 자정에 로그파일을 교체하며 기존파일은 xx.log_2004.07.12

log4j.appender.hoho.Threshold=DEBUG
//출력할 정보의 최소단위.


소스

log4j.rootLogger = info, stdout, dailyfile

log4j.stdout = false
log4j.debug = false

log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p ({%t} %F[%M]:%L) [%d] HIHI- %m%n

log4j.appender.dailyfile.Threshold = ERROR
log4j.appender.dailyfile = org.apache.log4j.DailyRollingFileAppender
log4j.appender.dailyfile.File = c:\\log\\logfile.log
log4j.appender.dailyfile.layout = org.apache.log4j.PatternLayout
log4j.appender.dailyfile.layout.ConversionPattern=%5p ({%t} %F[%M]:%L) [%d]  - %m%n

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


log4j.logger.log4j.bae=DEBUG, BAE

log4j.appender.BAE=org.apache.log4j.DailyRollingFileAppender
log4j.appender.BAE.File=C:/logs/BAE.log
log4j.appender.BAE.DatePattern='.'yyyy-MM-dd
log4j.appender.BAE.Threshold=DEBUG
log4j.appender.BAE.layout=org.apache.log4j.PatternLayout
log4j.appender.BAE.layout.ConversionPattern=[%d] %-5p %l - %m%n

log4j.logger.log4j.hehe=INFO, HEHE

log4j.appender.HEHE=org.apache.log4j.DailyRollingFileAppender
log4j.appender.HEHE.File=C:/logs/HEHE.log
log4j.appender.HEHE.DatePattern='.'yyyy-MM-dd
log4j.appender.HEHE.Threshold=DEBUG
log4j.appender.HEHE.layout=org.apache.log4j.PatternLayout
log4j.appender.HEHE.layout.ConversionPattern=[%d] %-5p %l - %m%n

http://blog.naver.com/skykingkjs?Redirect=Log&logNo=150152227953
[출처] [개발툴][Log4j] 로그4J properties 설정법.|작성자 카루



출처 - http://yth2626.blogspot.kr/2013/01/log4jproperties.html







Thursday, February 22, 2007

Log4J Logger vs. Category

Logging is the practice of recording sequential data. This is also a low-tech method of debugging and in some cases also the only way as the proper debugging tools may not be always available or applicable. Logging in Java can range from simple System.out.println() statements to usage of sophisticated logging frameworks.

At the time of writing there are several logging frameworks for logging in Java available. There is a popular and probably the most widely used Log4J framework. Younger brother of Log4J is the Java'sLogging API that became part of Java SE in version 1.4. See How does the Java logging API stack up against log4j for comparison. The are many other logging frameworks: SimpleLogjLoProtomatter Syslog, etc.

There are also several frameworks that enable abstraction from logging frameworks, also known as logging bridges(Apache Commons Logginglog-bridge). These allow switching between logging frameworks. These and many others can be found at Open Source Logging Tools in Java at java-source.net.

Log4J was one of the early logging frameworks that gained popularity and is present in many source code bases. In some cases you could encounter usage of Category class rather than Logger. If you work or worked on projects that are built on top of relatively young frameworks, you may not even know that Category class exists as its natural habitat is in old Java code. I hadn't known that Category class existed until I saw it one day. I saw it in a place where I would usually use Logger class. Since that day I kept reminding myself to look at it and see what's different from Logger class and why would one use it.

So what is the difference between Category and Logger classes? The Java documentation in Category class states

This class has been deprecated and replaced by the Logger subclass. It will be kept around to preserve backward compatibility until mid 2003.

Logger is a subclass of Category, i.e. it extends Category. In other words, a logger is a category. Thus, all operations that can be performed on a category can be performed on a logger. Internally, whenever log4j is asked to produce a Category object, it will instead produce a Logger object. Log4j 1.2 will never produce Category objects but only Logger instances. In order to preserve backward compatibility, methods that previously accepted category objects still continue to accept category objects.

Then the following example shows how Category was used and how Logger should be used.

// Deprecated form:
Category cat = Category.getInstance("foo.bar");

// Preferred form for retrieving loggers:
Logger logger = Logger.getLogger("foo.bar");

And that's it. That's all you have to do to replace Category with Logger (apart from renaming the variable).

The documentation also says

There is absolutely no need for new client code to use or refer to the Category class. Whenever possible, please avoid referring to it or using it.

Why is this important? The plan is that from Log4J version 1.3 Category class will be removed! What can we do to prepare our code for Log4J 1.3? Well Preparing for Log4J version 1.3 has it all spelled out. It's worth to read if you want to understand all implications this upgrade may have. I just shamelessly paste the steps here:

  1. Never refer to the Category class directly, refer to Logger instead.
  2. Do not invoke the deprecated Category.getRoot method. Invoke Logger.getRootLogger method instead.
  3. Do not invoke the deprecated Category.getInstance(String) method. InvokeLogger.getLogger(String) method instead.
  4. Do not invoke the deprecated Category.getInstance(Class) method. InvokeLogger.getLogger(Class) method instead.
  5. Never refer to the Priority class, refer to Level class instead.
  6. Do not invoke the deprecated Category.setPriority(Priority) method. InvokeLogger.setLevel(Level) method instead.
  7. Do not invoke the deprecated Priority.toPriority(int) method. Invoke Level.toLevel(int) method instead. The same holds true for the other variants of the Priority.toPriority method.
  8. Never refer to the deprecated Priority.FATALPriority.ERRORPriority.WARN,Priority.INFOPriority.DEBUG fields. Refer to the Level.FATALLevel.ERROR,Level.WARNLevel.INFOLevel.DEBUG fields instead.

  9. If you confiugure appenders programmatically, do not forget to invoke the activateOptions method of an appender after you have instantiated it and set its options.

and as the above mentioned document says

For 99.99% of users, this translates to the following string find-and-replace operations:
  1. Replace the string "Category.getInstance" with the string "Logger.getLogger".
  2. Replace the string "Category.getRoot" with the string "Logger.getRootLogger".
  3. Replace the string "Category" with the string "Logger".
  4. Replace the string "Priority" with the string "Level".

Happy logging!


source - http://hanuska.blogspot.kr/2007/02/log4j-logger-vs-category.html







'Framework & Platform > Common' 카테고리의 다른 글

OSGi(Open Service Gateway initiative)  (0) 2012.03.25
모델1과 모델2의 차이점  (0) 2012.03.21
디자인 패턴  (0) 2012.03.18
Refactoring  (0) 2012.03.18
Struts 2 따라잡기  (0) 2010.12.26
Posted by linuxism
,