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

What's the use of log4j?

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

Share

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

Editor to share with you what is the use of 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!

The role of usage logs of log4j

It is convenient to analyze the process of program execution.

Easy to debug

Business data can be stored in files and databases, which is beneficial to post-analysis.

Introduction to log4j

Log4j is an open source project of Apache that specifies which types of logs are output by setting the log level. Log4j is powerful:

You can output log information to the console, files, GUI components, or even databases

You can control the output format of each log

Log level of log4j

Log4j defines seven log levels in the org.apache.log4j.Level class, from high to low:

The highest log level of OFF, that is, turn off logging

The error that FATAL caused the application to exit

An error occurred in the operation of ERROR, but it still does not affect the continued operation of the system (program).

WARN warnings, that is, potential error situations

INFO is generally used at the coarse-grained level to record the whole execution process of the program and emphasize the whole running process of the application.

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

Minimum log level of ALL, logging for all levels

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

The composition of log4j

Log4j is mainly composed of three parts:

(1) Loggers (logger) controls the output level of the log and whether the log is output.

(2) Appenders (output side) specifies where the log is output (to the console, files, etc.). The commonly used output side is:

ConsoleAppender outputs logs to the console

FileAppender outputs logs to a file

RollingFileAppender outputs log information to a file and specifies the file size. When the file size reaches the specified size, it automatically renames the file and creates a new file to save the log.

DailyRollingFileAppender outputs the log to a file and periodically to a new file

JDBCAppender saves the log information to the database

(3) Layout (log formatter), a common type of formatter:

HTMLLayout format log output to HTML form

SimpleLayout simple log output formatting

PatternLayout's most powerful formatter, customizable log output format

Example of using log4j

(1) download log4j and import log4j.jar

Note that it is log4j, not log4j2.

The author of log4j first developed log4j, with the version number starting with 1. Later, log4j is refactored to improve the deficiency of log4j, that is, log4j2, with the version number starting with 2. The usage of log4j is quite different from that of log4j2.

Download log4j, some versions contain log4j.jar, log4j-core.jar, log4j-api.jar3 jar package, we just need to import log4j.jar.

(2) the configuration file log4j.properties of the new log4j under src

# Global setting of the logger Logger # the first parameter specifies the minimum log level of the output, that is, only logs at that level and above are output. The parameter after # specifies which configuration to be made log4j.rootLogger = DEBUG,stdout,D,E### Settings console output # stdout is standard out standard output, which defaults to the console. So you can replace stdout with Consolelog4j.appender.stdout = org.apache.log4j.ConsoleAppender# specify standard output device as system output device log4j.appender.stdout.Target = System.out# specify use custom formatter log4j.appender.stdout.layout = org.apache.log4j.PatternLayout# specify log output format log4j.appender.stdout.layout.ConversionPattern = [%-5p]% d {yyyy-MM-dd HH:mm:ss When SSS} method:%l%n%m%n### outputs logs of DEBUG or above to D://logs/debug.log#### configuration The output level is represented by the initials D that is, DEBUGlog4j.appender.D = org.apache.log4j.DailyRollingFileAppender# specifies the file to which the log is output log4j.appender.D.File = D://logs/debug.log# specifies how the file is written appends log4j.appender.D.Append = true# specifies the lowest output level log4j.appender.D.Threshold = DEBUG log4j.appender.D.DatePattern='.'yyyy-MM-dd-HH-mm# specifies the log output format log4j.appender.D.layout = org.apache.log4j.SimpleLayout # output logs of ERROR and above to D://logs/error.log # log4j.appender.E = org.apache.log4j.RollingFileAppenderlog4j.appender.E.File = D://logs/error.log log4j.appender.E.Append = truelog4j.appender.E.Threshold = ERROR # specify the maximum size of the log file log4j.appender.E.MaxFileSize = 2KB# specify the maximum number of backups as 5log4j.appender.E.MaxBackupIndex = 5 # specify log output format using custom format log4j.appender.E.layout = org.apache.log4j.PatternLayout# specify log format log4j.appender.E.layout.ConversionPattern =% d {yyyy-MM-dd HH:mm:ss} [% tblog% r]-[% p]% m% n

This configuration is for demonstration purposes only.

Options unique to DailyRollingFileAppender

DatePattern='.'yyyy-ww

Optional values:

'. Yyyy-MM every month

Yyyy-ww every week

Yyyy-MM-dd every day

Yyyy-MM-dd-a twice a day

Yyyy-MM-dd-HH per hour

Yyyy-MM-dd-HH-mm per minute

For example,'. 'yyyy-MM-dd-HH-mm generates a new file with the same name every minute to save the log during that minute.

A new file with the same name? Is to add time after the extension, to see that you need to change the extension.

If there is no log output during this minute, no new file is created.

Options unique to RollingFileAppender

# specify the maximum size of log files MaxFileSize = 2KB# specify the maximum number of backups as 5MaxBackupIndex = 5

The original file is error.log, and when you reach the specified maximum size, rename the file to error.log.1 (with an index after the extension), and create a new error.log to save the log.

After error.log reaches its maximum size, rename error.log.1 to error.log.2, rename error.log to error.log.1, and create a new error.log to save the log.

.

There can be up to 5 backups (1, 2, 3, 4, 5).

With 5 backups, if error.log reaches its maximum size, delete error.log.5, rename error.log.4 to error.log.5,error.log.3, rename error.log.4.error.log to error.log.1, and create a new error.log to save the log.

Log output format

HTMLLayout

Output the log to the specified file in the form of html code, and change the file extension to .html to see the effect:

SimpleLayout

Level-Log Information

DEBUG-This is debug message.INFO-This is info message.ERROR-This is error message.PatternLayout

The custom format, similar to the C language printf (), uses placeholders:

Log information specified in m code

% p log level, DEBUG, INFO, etc.

% n newline character

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

T the full name of the thread that generated the log

% d server current time, format can be specified later, such as% d {yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

Where the% l 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 file name of the file in which the log message was generated

% L code line number

%% output one%

You can specify the width and alignment:

The width of 5p is 5, and when the number of characters is less than 5, the default right alignment

The width of%-5p is 5, and when the number of characters is less than 5, left alignment

(3) create a new test class test.Log4jTest under src

Package test;import org.apache.log4j.Logger;public class Log4jTest {public static void main (String [] args) {/ / get Logger Logger logger = Logger.getLogger (Log4jTest.class) of the current class; / / output DEBUG-level log with the parameter logger.debug ("This is debug message."); / / output INFO-level log logger.info ("This is info message.") / / output ERROR-level log logger.error ("This is error message.");}}

Description

Log4j can be used alone, and when used alone, you only need to add the log4j.jar package.

If you want to use log4j in other frameworks, you usually also download the commons-logging.jar that adds apache.

Because log4j realizes the function of logging, commons-logging.jar defines the log interface, commons-logging itself does not have the function of logging, the relationship between them is the relationship between interface and implementation class, and the introduction of commons-logging.jar reduces the coupling between framework and log from class to interface.

Common configuration of log4j is attached

# Global setting of logger Logger # log4j.rootLogger = DEBUG,stdout,D,E### Settings console output # log4j.appender.stdout = org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target = System.outlog4j.appender.stdout.layout = org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern = [%-5p]% d {yyyy-MM-dd HH:mm:ss SSS} method:%l%n%m%n### outputs logs of DEBUG and above to file # log4j.appender.D = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.D.File = D://log/debug/debug.log log4j.appender.D.Append = truelog4j.appender.D.Threshold = ERRORlog4j.appender.D.DatePattern='.'yyyy-MM-ddlog4j.appender.D.layout = org.apache.log4j.PatternLayoutlog4j.appender.D.layout.ConversionPattern =% d {yyyy-MM-dd HH:mm:ss} [% tlog4j.appender.E% r]-[% p]% m% n # output logs of ERROR and above to file # log4j.appender.E = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.E.File = D://log/error/error.log log4j.appender.E.Append = truelog4j.appender.E.Threshold = ERRORlog4j.appender.E.DatePattern='.'yyyy-MM- Ddlog4j.appender.E.layout = org.apache.log4j.PatternLayoutlog4j.appender.E.layout.ConversionPattern =% d {yyyy-MM-dd HH:mm:ss} [% tyyyy-MM-dd HH:mm:ss% r]-[% p]% m% n is all the content of the article "what's the use of log4j"? Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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