Discussion on the use of LOG4J in JAVA project

  • 2020-05-19 04:56:54
  • OfStack

1. Direct use:


// Output to the project folder output1.txt In the file 

//////////////////////////////

// DEBUG - Here is some DEBUG

// INFO - Here is some INFO

// WARN - Here is some WARN

// ERROR - Here is some ERROR

// FATAL - Here is some FATAL

//////////////////////////////

package hunnu.sanha.test;

import org.apache.log4j.Level;

import org.apache.log4j.Logger;

import org.apache.log4j.SimpleLayout;

import org.apache.log4j.FileAppender;

public class Simpandfile {

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

 public static void main(String args[]) {

  SimpleLayout layout = new SimpleLayout();

  FileAppender appender = null;

  try {

   appender = new FileAppender(layout,"output1.txt",false);

  } catch(Exception e) {}

  logger.addAppender(appender);

  logger.setLevel((Level) Level.);

  logger.debug("Here is some DEBUG");

  logger.info("Here is some INFO");

  logger.warn("Here is some WARN");

  logger.error("Here is some ERROR");

  logger.fatal("Here is some FATAL");

 }

}

 

// Format the output to the project folder output2.html

package hunnu.sanha.test;

import java.io.*;

import org.apache.log4j.Level;

import org.apache.log4j.Logger;

import org.apache.log4j.HTMLLayout;

import org.apache.log4j.WriterAppender;

public class Htmlandwrite {

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

 public static void main(String args[]) {

  HTMLLayout layout = new HTMLLayout();

  WriterAppender appender = null;

  try {

   FileOutputStream output = new FileOutputStream("output2.html");

   appender = new WriterAppender(layout,output);

  } catch(Exception e) {}

  logger.addAppender(appender);

  logger.setLevel((Level) Level.);

  logger.debug("Here is some DEBUG");

  logger.info("Here is some INFO");

  logger.warn("Here is some WARN");

  logger.error("Here is some ERROR");

  logger.fatal("Here is some FATAL");

 }

}

 

 

// Output to console 

////////////////////////////////////////////////////////////////////////////////////////////////////////////

Milliseconds since program start: 0

Classname of caller: hunnu.sanha.test.Consandpatt

Date in ISO8601 format: 2008-07-29 11:02:30,578

Location of log event: hunnu.sanha.test.Consandpatt.main(Consandpatt.java:20)

Message: Here is some DEBUG

 

Milliseconds since program start: 15

Classname of caller: hunnu.sanha.test.Consandpatt

Date in ISO8601 format: 2008-07-29 11:02:30,593

Location of log event: hunnu.sanha.test.Consandpatt.main(Consandpatt.java:21)

Message: Here is some INFO

 

Milliseconds since program start: 15

Classname of caller: hunnu.sanha.test.Consandpatt

Date in ISO8601 format: 2008-07-29 11:02:30,593

Location of log event: hunnu.sanha.test.Consandpatt.main(Consandpatt.java:22)

Message: Here is some WARN

 

Milliseconds since program start: 15

Classname of caller: hunnu.sanha.test.Consandpatt

Date in ISO8601 format: 2008-07-29 11:02:30,593

Location of log event: hunnu.sanha.test.Consandpatt.main(Consandpatt.java:23)

Message: Here is some ERROR

 

Milliseconds since program start: 15

Classname of caller: hunnu.sanha.test.Consandpatt

Date in ISO8601 format: 2008-07-29 11:02:30,593

Location of log event: hunnu.sanha.test.Consandpatt.main(Consandpatt.java:24)

Message: Here is some FATAL

///////////////////////////////////////////////////////

package hunnu.sanha.test;

import org.apache.log4j.Level;

import org.apache.log4j.Logger;

import org.apache.log4j.PatternLayout;

import org.apache.log4j.ConsoleAppender;

public class Consandpatt {

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

 public static void main(String args[]) {

  // Note, %n is newline

  String pattern = "Milliseconds since program start: %r %n";

    pattern += "Classname of caller: %C %n";

    pattern += "Date in ISO8601 format: %d{ISO8601} %n";

    pattern += "Location of log event: %l %n";

    pattern += "Message: %m %n %n";

  

  PatternLayout layout = new PatternLayout(pattern);

  ConsoleAppender appender = new ConsoleAppender(layout);

  logger.addAppender(appender);

  logger.setLevel((Level) Level.);

  logger.debug("Here is some DEBUG");

  logger.info("Here is some INFO");

  logger.warn("Here is some WARN");

  logger.error("Here is some ERROR");

  logger.fatal("Here is some FATAL");

 }

}

2. Use configuration files (all directly under the project folder)


//xmllog4jconfig.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

 <appender name="appender" class="org.apache.log4j.FileAppender">

  <param name="File" value="Indentify-Log.txt"/>

  <param name="Append" value="false"/>

  <layout class="org.apache.log4j.PatternLayout">

  <param name="ConversionPattern" value="%d [%t] %p - %m%n"/>

  </layout>

 </appender>

 <root>

  <priority value ="debug"/>

  <appender-ref ref="appender"/>

 </root>

</log4j:configuration>

 

//Externalxmltest.java

 package hunnu.sanha.external;

import org.apache.log4j.Logger;

import org.apache.log4j.xml.DOMConfigurator;

public class Externalxmltest {

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

 public static void main(String args[]) {

  DOMConfigurator.configure("xmllog4jconfig.xml");

  logger.debug("Here is some DEBUG");

  logger.info("Here is some INFO");

  logger.warn("Here is some WARN");

  logger.error("Here is some ERROR");

  logger.fatal("Here is some FATAL");

 }

}

// The result is output to Indentify-Log.txt In the file 

2008-07-29 10:48:11,375 [main] DEBUG - Here is some DEBUG

2008-07-29 10:48:11,375 [main] INFO - Here is some INFO

2008-07-29 10:48:11,375 [main] WARN - Here is some WARN

2008-07-29 10:48:11,375 [main] ERROR - Here is some ERROR

2008-07-29 10:48:11,375 [main] FATAL - Here is some FATAL

 

 

// plainlog4jconfig.txt

# initialise root logger with level DEBUG and call it BLAH

log4j.rootLogger=DEBUG, BLAH

# add a ConsoleAppender to the logger BLAH

log4j.appender.BLAH=org.apache.log4j.ConsoleAppender

# set set that layout to be SimpleLayout

log4j.appender.BLAH.layout=org.apache.log4j.SimpleLayout

 

//Externalplaintest.java

package hunnu.sanha.external;

import org.apache.log4j.Logger;

import org.apache.log4j.PropertyConfigurator;

public class Externalplaintest {

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

 public static void main(String args[]) {

  PropertyConfigurator.configure("plainlog4jconfig.txt");

  logger.debug("Here is some DEBUG");

  logger.info("Here is some INFO");

  logger.warn("Here is some WARN");

  logger.error("Here is some ERROR");

  logger.fatal("Here is some FATAL");

 }

}

// The result is output to the console 

DEBUG - Here is some DEBUG

INFO - Here is some INFO

WARN - Here is some WARN

ERROR - Here is some ERROR

FATAL - Here is some FATAL

Additional:

2.1. Priority of log information

It is divided into OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL, or whatever level you define.
Log4j recommends using only four levels, with priority ranging from high to low: ERROR, WARN, INFO, DEBUG. With the level defined here, you can control the switch to log information at the appropriate level in your application.
Suppose a log request of level p occurs in an Logger with level q, if p > =q, then the request will be enabled. This is the core principle of Log4j.
For example, if the INFO level is defined here, all the log information at the DEBUG level in the application will not be printed;

2.2. Use of output source

Selective availability or disabling of log requests is only part of part 1 of Log4j. Log4j allows log requests to be output to multiple output sources. In the words of Log4j, an output source is called an Appender.
Appender includes console (console), files (file), GUI components (graphical component), remote socket servers (socket service), JMS


//xmllog4jconfig.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

 <appender name="appender" class="org.apache.log4j.FileAppender">

  <param name="File" value="Indentify-Log.txt"/>

  <param name="Append" value="false"/>

  <layout class="org.apache.log4j.PatternLayout">

  <param name="ConversionPattern" value="%d [%t] %p - %m%n"/>

  </layout>

 </appender>

 <root>

  <priority value ="debug"/>

  <appender-ref ref="appender"/>

 </root>

</log4j:configuration>

 

//Externalxmltest.java

 package hunnu.sanha.external;

import org.apache.log4j.Logger;

import org.apache.log4j.xml.DOMConfigurator;

public class Externalxmltest {

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

 public static void main(String args[]) {

  DOMConfigurator.configure("xmllog4jconfig.xml");

  logger.debug("Here is some DEBUG");

  logger.info("Here is some INFO");

  logger.warn("Here is some WARN");

  logger.error("Here is some ERROR");

  logger.fatal("Here is some FATAL");

 }

}

// The result is output to Indentify-Log.txt In the file 

2008-07-29 10:48:11,375 [main] DEBUG - Here is some DEBUG

2008-07-29 10:48:11,375 [main] INFO - Here is some INFO

2008-07-29 10:48:11,375 [main] WARN - Here is some WARN

2008-07-29 10:48:11,375 [main] ERROR - Here is some ERROR

2008-07-29 10:48:11,375 [main] FATAL - Here is some FATAL

 

 

// plainlog4jconfig.txt

# initialise root logger with level DEBUG and call it BLAH

log4j.rootLogger=DEBUG, BLAH

# add a ConsoleAppender to the logger BLAH

log4j.appender.BLAH=org.apache.log4j.ConsoleAppender

# set set that layout to be SimpleLayout

log4j.appender.BLAH.layout=org.apache.log4j.SimpleLayout

 

//Externalplaintest.java

package hunnu.sanha.external;

import org.apache.log4j.Logger;

import org.apache.log4j.PropertyConfigurator;

public class Externalplaintest {

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

 public static void main(String args[]) {

  PropertyConfigurator.configure("plainlog4jconfig.txt");

  logger.debug("Here is some DEBUG");

  logger.info("Here is some INFO");

  logger.warn("Here is some WARN");

  logger.error("Here is some ERROR");

  logger.fatal("Here is some FATAL");

 }

}

// The result is output to the console 

DEBUG - Here is some DEBUG

INFO - Here is some INFO

WARN - Here is some WARN

ERROR - Here is some ERROR

FATAL - Here is some FATAL
(java information service), NT Event Loggers (NT event log), and remote UNIX Syslog daemons (remote UNIX background log service). It can also record asynchronously.
1 logger can set more than 1 appender.
Add 1 appender to 1 given logger using the addAppender method. For a given logger, each valid log request is forwarded to all appender of the logger and logger's appender of the logger parent.

2.2.1. ConsoleAppender


If ConsoleAppender is used, the log message is written to Console. The effect is equivalent to printing the information directly onto System.out.

2.2.2. FileAppender

Using FileAppender, log information is written to the specified file. This should be the case more often.
Accordingly, the file name for the log output should be specified in the configuration file. The following configuration specifies the log file name dglog.txt
log4j.appender.A2.File=dglog.txt
Note that A2 is replaced with the alias for Appender in the specific configuration.

2.2.3. DailyRollingAppender

Using FileAppender, you can output log information to a file, but it is difficult to read if the file is too large. You can use DailyRollingAppender. DailyRollingAppender can output Log information to a date-sensitive file. The configuration file will generate one log file every day, and each log file only records the log information on that day:
log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A2.file=dglog
log4j.appender.A2.DatePattern='.'yyyy-MM-dd
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern= %5r %-5p %c{2} - %m%n

2.2.4. org.apache.log4j.RollingFileAppender


A new file is generated when the file size reaches the specified size.
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File= ../logs/dglog.log
# Control the maximum log file size
log4j.appender.R.MaxFileSize=100KB
# Archive log files (one backup file here)
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
This configuration file specifies the output source R, which is a rotation log file. The largest file is 100KB. When a log file reaches the maximum size, Log4J will automatically rename example.log to dglog.log.1, and then rebuild a new dglog.log file in turn.

2.2.5. org.apache.log4j.WriterAppender

Sends log information in a stream format to any specified location.

2.3. Configuration of Layout

Layout specifies the style of the log message output.

2.3.1. Layout style

org. apache. log4j. HTMLLayout (layout) in the form of HTML form,
org. apache. log4j. PatternLayout (the flexibility to specify layout model),
org. apache. log4j. SimpleLayout string (including the level of logging information and information),
org. apache. log4j. TTCCLayout (contains the logs generated time, thread, categories, etc.)

2.3.2. Format


%m outputs the message specified in the code
The %p output priority is DEBUG, INFO, WARN, ERROR, FATAL
%r outputs the number of milliseconds it takes from application startup to the output of the log message
%c outputs the category to which it belongs, usually the full name of the class
%t outputs the name of the thread that produced the log event
%n outputs a carriage return newline character, Windows platform is "rn", Unix platform is "n"
% d output log time date or time, the default format for ISO8601, can also be specified in the subsequent format, for example: % d {yyy MMM dd HH: mm: ss, SSS}, similar to the output 22:10:28 on October 18, 2002, 921
%l outputs the location of the log event, including the class name, the thread that occurred, and the number of lines in the code. Example: Testlog4.main(Test Log4.java:10)

Example 2.3.3.

Example 1: display date and log information
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %m%n
The printed message is:
2002-11-12 11:49:42,866 SELECT * FROM Role WHERE 1=1 order by createDate desc

Example 2: shows the date, where log took place, and log information
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %l "#" %m%n
2002-11-12 11:51:46,313 cn.net.unet.weboa.system.dao.RoleDAO.select(RoleDAO.java:409) "#"
SELECT * FROM Role WHERE 1=1 order by createDate desc

Example 3: display log level, time, call method,log information
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS}
method:%l%n%m%n
log information:
[DEBUG] 2002-11-12 12:00:57,376
method:cn.net.unet.weboa.system.dao.RoleDAO.select(RoleDAO.java:409)
SELECT * FROM Role WHERE 1=1 order by createDate desc

2.4. Examples of configuration files:

log4j.rootLogger=DEBUG
Record DAO layer log to DAOLog,allLog
log4j.logger.DAO=DEBUG,A2,A4
Record logical layer log to BusinessLog,allLog
log4j.logger.Businesslog=DEBUG,A3,A4

#A1-- print to the screen
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-5p [%t] %37c %3x - %m%n

#A2-- print to file DAOLog -- specifically for the DAO layer
log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A2.file=DAOLog
log4j.appender.A2.DatePattern='.'yyyy-MM-dd
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS}
method:%l%n%m%n

#A3-- print to file BusinessLog -- specifically records the logical processing layer service log information
log4j.appender.A3=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A3.file=BusinessLog
log4j.appender.A3.DatePattern='.'yyyy-MM-dd
log4j.appender.A3.layout=org.apache.log4j.PatternLayout
log4j.appender.A3.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS}
method:%l%n%m%n

#A4-- print to file alllog -- record all log information
log4j.appender.A4=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A4.file=alllog
log4j.appender.A4.DatePattern='.'yyyy-MM-dd
log4j.appender.A4.layout=org.apache.log4j.PatternLayout
log4j.appender.A4.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS}
method:%l%n%m%n


Related articles: