Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Log4j

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you how to use Log4j, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Brief introduction

Log4J is an open source project of Apache (official website http://jakarta.apache.org/log4j). By using Log4J in the project, we can control the output of log information to the console, files, GUI components, and even databases. We can control the output format of each log. By defining the output level of the log, we can control the output process of the log more flexibly. Facilitate the debugging of the project.

Composition

Log4J is mainly composed of Loggers (logger), Appenders (output) and Layout (log formatter). Loggers controls the output level of the log and whether the log is output; Appenders specifies the output mode of the log (output to console, files, etc.); Layout controls the output format of log information.

Log level

Log4J defines seven log levels of OFF, FATAL, ERROR, WARN, INFO, DEBUG and all in the org.apache.log4j.Level class:

OFF maximum log level, turn off the left and right logs

An error that FATAL will cause the application to exit

An error event occurred in ERROR, but still did not affect the continued operation of the system

WARN warnings, that is, potential error situations

INFO generally and at the coarse-grained level emphasizes the whole running process of the application.

DEBUG is generally used at the fine-grained level and is very helpful for debugging applications

Minimum ALL level, turn on all logging

Note: generally, only 4 levels are used, and the priority from high to low is ERROR > WARN > INFO > DEBUG.

Appender (output)

Appender is used to specify where the log is output, and you can also specify the output destination of the log. There are several common output destinations for Log4j:

Layout (log formatter)

Getting started

First introduce the dependency of log4j in maven:

Log4j log4j 1.2.17

Create a Log4jTest class to test the use of Log4j:

Public class Log4JTest {public static void main (String [] args) {/ / get the instance of Logger object Logger logger = Logger.getLogger (Log4JTest.class); / / use default configuration information without writing log4j.properties BasicConfigurator.configure () / / set the log output level to WARN, which will override the level set in the configuration file. Only logs whose log level is higher than WARN will output logger.setLevel (Level.WARN); logger.debug ("this is debug"); logger.info ("this is info"); logger.warn ("this is warn"); logger.error ("this is error"); logger.fatal ("this is fatal");}}

Here, we first create an Logger instance through Logger.getLogger (Log4Test.class), then call the BasicConfigurator.configure () method to specify that the Logger uses the default configuration information, and then call looger.setLevel (Level.WARN) to set the log output level of the Logger to WARN. Run the main function, and the console will output an error message above warn. The console output is as follows:

0 [main] WARN com.huang.log4j.Log4JTest-this is warn

0 [main] WARN com.huang.log4j.Log4JTest-this is error

0 [main] WARN com.huang.log4j.Log4JTest-this is fatal

Note: if the BasicConfigurator.configure () method is not called, there will be an error when running the main function, because the Log4j framework loads the log4j.properties configuration file under the project path at run time (the use of the configuration file will be explained later). We do not have this file in our project at this time. If the name of the profile is not log4j.properties, you can specify the name of the profile through PropertyConfigurator.configure (String configFilename).

The use of formatters

Modify the code in Log4JTest:

Public class Log4JTest {public static void main (String [] args) {Logger logger = Logger.getLogger (Log4JTest.class); BasicConfigurator.configure (); HTMLLayout layout = new HTMLLayout (); / / SimpleLayout layout = new SimpleLayout (); try {FileAppender appender = new FileAppender (layout, "D:\\ out.html", false); logger.addAppender (appender) / / set the log output level to info, which will override the level set in the configuration file. Only logs whose log level is higher than WARN will output logger.setLevel (Level.WARN); logger.debug ("this is debug"); logger.info ("this is info"); logger.warn ("this is warn"); logger.error ("this is error"); logger.fatal ("this is fatal") } catch (IOException e) {e.printStackTrace ();}

First create a formatter (HTMLLayout) in HTML format, and then create a file output (FileAppender) to specify that the output is in HTML format, where I specify the output path to be the out.html file under disk D. Then load the output side of the file into Logger through logger.addAppender (appender). Run the main function, and an out.html file will be generated under disk D, and the file will be opened. The information in it is the log information output in the code:

Use of log4j.properties profile

The above uses code to format the output of Logger, so it's too troublesome to set the configuration on each of the classes where we want to output the log. There is a more convenient way, we just need to create a new log4j.properties configuration file under the project path and configure the log output format and other information, the Log4J framework will automatically load the configuration file and set the configuration information to Logger. The simplest configuration file is as follows:

# console output configuration log4j.appender.Console=org.apache.log4j.ConsoleAppenderlog4j.appender.Console.layout=org.apache.log4j.PatternLayoutlog4j.appender.Console.layout.ConversionPattern=%d [% t]%-5p [% c] -% m% n # text output configuration log4j.appender.A = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.A.File = D:/log.txt # specify the output path of the log log4j.appender.A.Append = truelog4j.appender.A.Threshold = DEBUGlog4j.appender.A.layout = org.apache.log4j.PatternLayout # use the custom log formatter log4j.appender.A.layout.ConversionPattern =%-d {yyyy-MM-dd HH:mm:ss} [% tblog% r]-[% p]% m% n # specify the output format of the log log4j.appender.A.encoding=UTF-8 # specify the file encoding of the log # specify the output level of the log and output log4j.rootLogger=DEBUG Console,A

In the log4j.properties configuration file, we define the log output level and the output side, and configure the output format of the log on the output side.

Log4j formats the log information in a print format similar to the printf function in C language. The specific placeholders and their meanings are as follows:

% m outputs the log information specified in the code

% p output priority, and DEBUG, INFO, etc.

% n newline character (newline character is "\ n" for Windows platform and "\ n" for Unix platform)

% r output the number of milliseconds it took since the application was started to output the log information

C output the full name of the class to which the print statement belongs

T output the full name of the thread that generated the log

D output server current time, default format is ISO8601, or you can specify the format later. Such as:% d {yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

% l output where the log time occurs, including the class name, the thread that occurred, and the number of lines in the code, such as: Test.main (Test.java:10)

% F the name of the file in which the output log message was generated

% L output line number in code

% x outputs the NDC (nested diagnostic environment) associated with the current thread

%% outputs a'% 'character

You can add modifiers between% and characters to control the minimum width, maximum width, and how the text is aligned. Such as:

5c outputs the category name, with a minimum width of 5ther category

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report