Log4j 2.0 advanced usage in development-SocketAppender remote output (5), log4j configuration details

Source: Internet
Author: User

Log4j 2.0 advanced usage in development-SocketAppender remote output (5), log4j configuration details
Log4j2 Appenders fully consider the possibility of log event output, packaging, and filtering forwarding, including the most basic output to a local file and output to a remote host,
The file is encapsulated and injected, and automatically stored according to the log file time point, file size, and other conditions.
For example, if you want to collect several logs from different sources, you can use FlumeAppender; if you want to inject information in LogEvent,
You can use RewriteAppender. To enable the system to automatically seal log information at a specified interval, you can use RollingFileAppender
(A new log file is automatically saved at a certain time and named according to the specified format such as timestamp). When a LogEvent with a security level of ERROR or FATAL is generated,
SMTPAppender can be used to send emails to maintenance personnel; SocketAppender can be used to write logs to remote hosts; and log information can be sent to remote hosts in RFC5424 format,

SyslogAppender is available.

SocketAppender
Output the log event to a remote server (the server name and port number must be specified). Data can be sent in any specified format through TCP or UDP.
Key parameters in SocketAppender include:
(1) host, String, specifies the host Name of the server. (Required)
(2) immediateFlush, boolean, whether to flush immediately, or wait for the cache to a certain size before flush.
(3) layout, Layout, and log event output formats.
(4) port, integer, the port number of the application of the remote server's strong log event.
Protocol, String, the protocol used to send log events, "TCP" or "UDP ".
Optional reconnectionDelay, integer. Number of milliseconds that are waiting for delay when the connection is disconnected.
The name of Appender, String, and Appender.
Protocol, String, communication protocol default TCP. Optional values: "TCP" (default), "SSL" or "UDP ".
Secure SSL and SslConfiguration, including the configurations of the keystore and the trusted repository.
Producer filter, Filter, a filter to determine whether the event should be handled by this Appender. More than one filter can be used by using a CompositeFilter.
When immediateFail and boolean are set to true, log events will not wait for a try to reconnect and will immediately become unavailable if the socket fails.
⑿ ImmediateFlush, boolean. When this value is set to true, each write is rinsed by default. This ensures that the written data is sent to the disk, but may affect the performance.
The layout Layout, layout, and LogEvent are in the format. The default value is SerializedLayout.
⒁ ReconnectionDelay, integer. If it is set to a value greater than 0, SocketManager tries to reconnect to the server after the specified number of milliseconds after an error. If the connection fails, an exception will be thrown (it can be set to false by the application if ignoreExceptions ).
Events ignoreExceptions, boolean. The default value is true when an event is added, internal records that cause exceptions are encountered, and then ignored. If it is set to false, it will be propagated to the abnormal caller. You must set this token to wrap the AppenderFailoverAppender.

Log server code (main method ):

package com.herman.log4j2.server;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;public class TestServer {    public static void main(String[] args) throws IOException {    ServerSocket socket = new ServerSocket(5000);        while (true) {        Socket client = socket.accept();        Thread t = new Thread(new LogRunner(client));        t.start();        }}}
Log server code (Runnable thread ):

Package com. herman. log4j2. server; import java. io. IOException; import java. io. interruptedIOException; import java. io. objectInputStream; import java.net. socket; public class LogRunner implements Runnable {private ObjectInputStream ois; public LogRunner (Socket client) {try {this. ois = new ObjectInputStream (client. getInputStream ();} catch (Exception e) {e. printStackTrace () ;}} public void run () {try {while (true) {Object obj = ois. readObject (); System. out. println (obj. toString () ;}} catch (java. io. EOFException e) {// catch (java.net. socketException e) {} catch (InterruptedIOException e) {Thread. currentThread (). interrupt ();} catch (IOException e) {} catch (Exception e) {e. printStackTrace () ;}finally {}}}
Client xml configuration (log4j2. xml ):
<? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <! -- Appenders output Destination --> <Appenders> <! -- Configure the name of the log output file to append the read/write host address port --> <Socket name = "A1" host = "localHost" port = "5000"> <! -- Output format sequence layout --> <SerializedLayout/> </Socket> <! -- Console output --> <Console name = "STDOUT" target = "SYSTEM_OUT"> <! -- Output format layout --> <PatternLayout pattern = "% d %-5 p [% t] % C {2} (% F: % L) -% m % n "/> </Console> </Appenders> <Loggers> <! -- Debug level --> <Root level = "debug"> <AppenderRef ref = "A1"/> <AppenderRef ref = "STDOUT"/> </Root> </Loggers> </Configuration>
Client test code:

Package com. herman. log4j2. test; import org. apache. logging. log4j. logManager; import org. apache. logging. log4j. logger;/*** @ see log4j 2.0 simple configuration using a file Appender * @ author Herman. xiong * @ date July 21, 2014 14:32:55 */public class Test2 {/*** configure the log level as debug, and the output location is console and file */private static Logger log = LogManager. getLogger (Test2.class); public static void main (String [] args) {log. trace ("trace"); log. debug ("debug"); log.info ("info"); log. warn ("warn"); log. error ("error"); log. fatal ("fatal"); log. trace ("trace"); log. debug ("debug"); log.info ("info"); log. warn ("warn"); log. error ("error"); log. fatal ("fatal"); log. exit ();}}
Output result:

Logger=com.herman.log4j2.test.Test2 Level=DEBUG Message=debugLogger=com.herman.log4j2.test.Test2 Level=INFO Message=infoLogger=com.herman.log4j2.test.Test2 Level=WARN Message=warnLogger=com.herman.log4j2.test.Test2 Level=ERROR Message=errorLogger=com.herman.log4j2.test.Test2 Level=FATAL Message=fatalLogger=com.herman.log4j2.test.Test2 Level=DEBUG Message=debugLogger=com.herman.log4j2.test.Test2 Level=INFO Message=infoLogger=com.herman.log4j2.test.Test2 Level=WARN Message=warnLogger=com.herman.log4j2.test.Test2 Level=ERROR Message=errorLogger=com.herman.log4j2.test.Test2 Level=FATAL Message=fatal
Welcome to follow my blog !!!!

If you have any questions or problems, add the QQ group: 135430763 for feedback and learn together!






How to Use log4j

Log4j configuration files conflict. Is there any other log4j configuration in your classpath?

Log4j also allows log record requests to be printed to multiple output destinations. The output source is called by log4j. A recorder can have multiple output sources. If a log information can be processed by this recorder, the recorder sends this information to each output source owned by it and to a more advanced output source in the hierarchy. For example, if the root recorder uses the console as the output source, all logs that can be recorded will be printed to the console at least.

Configure the log output source with the Syntax:

Log4j. appender. appenderName = fully. qualified. name. of. appender. class log4j. appender. appenderName. option1 = value1... Log4j. appender. appenderName. option = valueN Log4j provides the following types of appender:

Org. apache. log4j. leleappender (console)
Org. apache. log4j. FileAppender (file)
Org. apache. log4j. DailyRollingFileAppender (a log file is generated every day)
Org. apache. log4j. RollingFileAppender (a new file is generated when the file size reaches the specified size)
Org. apache. log4j. WriterAppender (send log information to any specified place in stream format)
Org. apache. log4j. SocketAppender (Socket)
Org. apache. log4j. NtEventLogAppender (Event Log of NT)
Org. apache. log4j. JMSAppender (email)
Note that you can overwrite the default behavior so that the accumulated output source is no longer attached:

Log4j. additi.pdf. loggerName = false note: Do not append an output source to multiple recorders. Otherwise, the system will get the "Attempted to append to closed appender named xxx" information.

 
What is the log4jproperties file in jsp?

Apache provides us with a powerful log operation package-Log4j. As an open-source project of Apache, log4j allows us to control the log information delivery destination, including the console, files, GUI components, and even interface servers, NT Event recorders, and UNIX Syslog daemon processes; you can also easily control the output format of each log. By defining the level of each log information, you can control the log generation process in greater detail. The most interesting thing is that these can be configured flexibly through a configuration file, without the need to modify the application code.

In actual programming, you must define the configuration file before making Log4j really run in the system. The definition step is to use Logger, Appender, and Layout respectively. Log4j supports two configuration file formats: XML and java properties (key = value) [Java feature file (key = value )]. (Only the properties file is described here)
Bytes -----------------------------------------------------------------------------------------------------------------------------
1. Configure the root Logger

Its syntax is:
Log4j. rootLogger = [level], appenderName1, appenderName2 ,...
Level: indicates the log record priority, which can be OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL, or the level you define. We recommend that you use only four levels of Log4j. The priority ranges from high to low: ERROR, WARN, INFO, and DEBUG. By defining the level here, you can control the switch to the corresponding level of log information in the application. For example, if the INFO level is defined here, all DEBUG-level logs in the application will not be printed. AppenderName: specifies where the log information is output. You can specify multiple output destinations at the same time.
Example: log4j. rootLogger = info, A1, B2, C3
Slave --------------------------------------------------------------------------------------------------------------------------------
2. Configure the log output destination

Its syntax is:
Log4j. appender. appenderName = fully. qualified. name. of. appender. class //
"Fully. qualified. name. of. appender. class" can be used to specify one of the following five destinations:

1.org. apache. log4j. leleappender (console)
2.org. apache. log4j. FileAppender (file)
3.org. apache. log4j. DailyRollingFileAppender (a log file is generated every day)
4.org. apache. log4j. RollingFileAppender (a new file is generated when the file size reaches the specified size)
5.org. apache. log4j. WriterAppender (send log information to any specified place in stream format)

1. leleappender options
Threshold = WARN: specify the minimum output level of log messages.
... The remaining full text>
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.