javam

May 19, 2011

Log4j Tutorial – Writing different log levels in different log files | Javalobby

Filed under: javam.mixed — Etiketlər: , — -- @ 9:29 səhər

Log4j Tutorial – Writing different log levels in different log files

Log4j Tutorial – Writing different log levels in different log files | Javalobby.

Recently one of my blog reader Surisetty send me a question, asking me if it is possible to write log messages of different levels (info, debug, etc) into different log files? To answer his question, yes, it is possible. We can do this by extending the FileAppender class and writing our own logic.

Below is the proof of concept code written to demonstrate this. Before that, you can download the Eclipse project file to run this code in your environment.

Download the Source code

To write different log levels in different log files

  1. Create a custom Log4j appender extending FileAppender.
  2. In that, override the append() method and check for the log level before writing a log message. Based on the level, call the setFile() method to switch between corresponding log file.
  3. Also, use MDC to store the original log file name mentioned in the log4j.properties. This is needed because setFile()changes the log file name every time you call it. So, we need to keep a track of the original file name somehow. And, we can use Log4j MDC for this.

Custom Appender: LogLevelFilterFileAppender

print?

01.package com.veerasundar.log4j;
02. 
03. 
04.import java.io.File;
05.import java.io.IOException;
06. 
07.import org.apache.log4j.FileAppender;
08.import org.apache.log4j.Layout;
09.import org.apache.log4j.MDC;
10.import org.apache.log4j.spi.ErrorCode;
11.import org.apache.log4j.spi.LoggingEvent;
12. 
13./**
14.* This customized Log4j appender will seperate the log messages based on their
15.* LEVELS and will write them' into separate files. For example, all DEBUG
16.* messages will go to a file and all INFO messages will go to a different file.
17.*
18.* @author Veera Sundar | http://veerasundar.com
19.*
20.*/
21.public class LogLevelFilterFileAppender extends FileAppender {
22. 
23.private final static String DOT = ".";
24.private final static String HIPHEN = "-";
25.private static final String ORIG_LOG_FILE_NAME = "OrginalLogFileName";
26. 
27.public LogLevelFilterFileAppender() {
28. 
29.}
30. 
31.public LogLevelFilterFileAppender(Layout layout, String fileName,
32.boolean append, boolean bufferedIO, int bufferSize)
33.throws IOException {
34.super(layout, fileName, append, bufferedIO, bufferSize);
35.}
36. 
37.public LogLevelFilterFileAppender(Layout layout, String fileName,
38.boolean append) throws IOException {
39.super(layout, fileName, append);
40.}
41. 
42.public LogLevelFilterFileAppender(Layout layout, String fileName)
43.throws IOException {
44.super(layout, fileName);
45.}
46. 
47.@Override
48.public void activateOptions() {
49.MDC.put(ORIG_LOG_FILE_NAME, fileName);
50.super.activateOptions();
51.}
52. 
53.@Override
54.public void append(LoggingEvent event) {
55.try {
56.setFile(appendLevelToFileName((String) MDC.get(ORIG_LOG_FILE_NAME),
57.event.getLevel().toString()), fileAppend, bufferedIO,
58.bufferSize);
59.catch (IOException ie) {
60.errorHandler
61..error(
62."Error occured while setting file for the log level "
63.+ event.getLevel(), ie,
64.ErrorCode.FILE_OPEN_FAILURE);
65.}
66.super.append(event);
67.}
68. 
69.private String appendLevelToFileName(String oldLogFileName, String level) {
70.if (oldLogFileName != null) {
71.final File logFile = new File(oldLogFileName);
72.String newFileName = "";
73.final String fn = logFile.getName();
74.final int dotIndex = fn.indexOf(DOT);
75.if (dotIndex != -1) {
76.// the file name has an extension. so, insert the level
77.// between the file name and the extension
78.newFileName = fn.substring(0, dotIndex) + HIPHEN + level + DOT
79.+ fn.substring(dotIndex + 1);
80.else {
81.// the file name has no extension. So, just append the level
82.// at the end.
83.newFileName = fn + HIPHEN + level;
84.}
85.return logFile.getParent() + File.separator + newFileName;
86.}
87.return null;
88.}
89.}

log4j.properties file

print?

1.log4j.rootLogger = DEBUG, fileout
2.log4j.appender.fileout = com.veerasundar.log4j.LogLevelFilterFileAppender
3.log4j.appender.fileout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c - %m%n
4.log4j.appender.fileout.layout = org.apache.log4j.PatternLayout
5.log4j.appender.fileout.File = C:/vraa/temp/logs.log

Lets test our code

print?

01.package com.veerasundar.log4j;
02. 
03.import org.apache.log4j.Logger;
04. 
05.public class Log4jDemo {
06. 
07.private static final Logger logger = Logger.getLogger(Log4jDemo.class);
08. 
09.public static void main(String args[]) {
10.logger.debug("This is a debug message");
11.logger.info("This is a information message");
12.logger.warn("This is a warning message");
13.logger.error("This is an error message");
14.logger.fatal("This is a fatal message");
15.logger.debug("This is another debug message");
16.logger.info("This is another information message");
17.logger.warn("This is another warning message");
18.logger.error("This is another error message");
19.logger.fatal("This is another fatal message");
20.}
21.}

 Download the Source code

From http://veerasundar.com/blog/2011/05/log4j-tutorial-writing-different-log-levels-in-different-log-files/

Advertisements

Noyabr 29, 2010

JAVA 7 – Yeniliklər

Filed under: javam.mixed, javam.news — Etiketlər: , , , — -- @ 2:17 axşam

Java 7Bu yazıda biraz Java 7-dəki yeniliklərdən bəhs edəcəyik. Qeyd edək ki, bu versiyanın kod adı Dolphin adlanır. Bu proyekt 2006 Avqust tarixində başlayıb və 2011 ortalarında ilk release hazır olacaq.

  • JDK 1.0 – Oak (Yanvar 23, 1996)
  • J2SE 1.2 – Playground (Dekabr 8, 1998)
  • J2SE 1.3 – Kestel (May 8, 2000)
  • J2SE 1.4 – Merlin (Fevral 6, 2002)
  • J2SE 5.0 – Tiger (Sentyabr 30, 2004)
  • Java SE 6 – Mustang (Dekabr 11, 2006)
  • Java SE 7.0 – Dolphin (2011 ortaları)
  • Java SE 8.0 – (2012 sonu)

Başlıca dəyişikliklər bunlardır:

  • Garbage-First GC (G1 garbage collector) daha performanslıdı
  • Dinamik dillərə JVM dəstəyi, Multi Language Virtual Machine (more…)

Noyabr 24, 2010

Oracle Announces JSRs for Java 7 and Java 8

Filed under: javam.news — Etiketlər: , — -- @ 10:28 səhər

Oracle has announced the umbrella JSRs for Java 7/8, covering a number of the features known from the earlier Plan B. The way JavaSE and JavaEE specifications are defined are by reference to other JSRs, rather than defining new content directly – but often will do so after those referenced JSRs are completed. In this case, many of the referenced JSRs are still works-in-progress, or in the case of modularity, not even known at this stage.

JSR 336, Java 7, has proposed to include:

(more…)

İyul 22, 2010

JEditorPane prevent blocks insert/replace/remove

Filed under: javam.swing — Etiketlər: , , , , , — -- @ 8:07 səhər

For preventing some parts of JEditorPane you can set document filter like that:

((AbstractDocument)jEditorPane.getDocument()).setDocumentFilter(myFilter);

We have html source like that:

<html>
<body>
  <h2>Hello World!!</h2>
  <span type="reserved">This area is guarded html block of JEditorPane</span>
  <p>You can change there</p>
  <span type="reserved">
    <form>
       Name:<input type="text"  name="name"/></br>
       Surname:<input type="text"  name="surname"/></br>
       <input type="submit"  name="submit" value="Ok"/>
    </form>
  </span>
</body>
</html>

(more…)

Aprel 5, 2010

Compile edilmiş class-ın jvm versiyasını götürmək

Filed under: javam.mixed — Etiketlər: , , — -- @ 6:55 səhər

Kodumuz aşağıdakı kimi yazılıb, onu java 1.5-də compile edirik.

package com.wordpress.javam;

public class HelloJavam {
  public static void main(String[] args) {
    System.out.println("Hello Javam!!!");
  }
}

Compile edilmiş hər hansı classın hansı versiya ilə compile edildiyini bilmək üçün aşağıdakı yoldan istifadə etmək olar: (more…)

WordPress.com-da pulsuz sayt və ya bloq yarat.

%d bloqqer bunu bəyənir: