Springboot | The 25th Chapter: the Custom Appender of log management

Source: Internet
Author: User
Objective

In the previous two chapters, we introduce some common configuration and usage practices of log frameworks. Generally, in the development process, the like log4j2 , the logback log framework provides a lot Appender , basically can meet the majority of business needs. But in some special needs or need to be centralized management of the log (cluster deployment, the log is split to different servers, it is not possible to go to each server to download files, and not easy to log retrieval), you need to customize Appender , the log set output or some other special needs. So this section provides a brief introduction to log4j2 logback the custom knowledge of and Appender .

    • A little knowledge
      • Log4j2 comes with Appender
      • Logback comes with Appender
    • Custom Appender
      • LOG4J2 Custom Appender
      • Logback Custom Appender
      • About Shutdownhook
        • A little knowledge
    • Resources
    • Summarize
    • At last
    • Cliché
A little knowledge

When writing customizations Appender , we first look at log4j2 and logback bring in what we have Appender , to see if we can meet our individual needs and avoid duplicating the wheels.

Log4j2 comes with Appender

Take a look at the instructions provided by the official website Appender :

name Description
Asyncappender Log events are processed asynchronously by using a separate thread for logging.
Cassandraappender Output log information to an Apache Cassandra database
Consoleappender Output log information to the console
Failoverappender Include other appenders, try sequentially, until successful or end
Fileappender A outputstreamappender that outputs the log to a file
Flumeappender Output logs to Apache flume system
Jdbcappender Output logs to a relational database through JDBC
JMS Appender Output logs to JMS (Java Message Service)
Jpaappender Output logs to the JPA framework
Httpappender Output logs via HTTP
Kafkaappender Output logs to Apache Kafka
Memorymappedfileappender Output the log to a piece of file associated memory
Outputstreamappender Output the log to a OutputStream
Randomaccessfileappender 20%~200% file output with higher performance than Fileappender Appender
Rewriteappender Allows processing of log information
Rollingfileappender Create a new file by the maximum length of the log file
Rollingrandomaccessfa Added Cached Rollingfileappender
Routingappender Classify log events and assign to sub-appender by condition
Smtpappender Output a log to a message
Socketappender Output the log to a socket
Syslogappender is a socketappender that outputs logs to the remote system log
ZEROMQ/JEROMQ Appender Output logs to the ZEROMQ terminal using the JEROMQ library

It has basically covered 90% of business scenarios. For detailed instructions or to configure your own search or check the official website description.
Website address: http://logging.apache.org/log4j/2.x/manual/appenders.html

Logback comes with Appender

And the log4j2 same, the self-bring is almost.

name description
Consoleappender output log to console
fileappender output log to file
rollingfileappender Scroll file generation, conditionally generate different files, with Triggeringpolicy use
socketappender output log to remote instance, clear text transfer
Sslsocketappender output log to remote instance, ciphertext transfer
smtpappender output log to mail
dbappender log events are inserted into the database, you need to create the table in advance
Syslogappender is a socketappender, output the log to the remote system log
Siftingappender can separate (or filter) logs based on any given real-time attribute, such as separating log events based on user session
amqpappender output log to MQ service

Specific to view: 73327752 very detailed!

or view official website: logback.qos.ch/manual/appenders.html

Custom Appender

When customizing Appender , you can follow the implementation of the function, the appropriate inheritance ( log4j2 the appender class is basically set to final not inherit) or reference some of the existing functions, of course, can also directly inherit its base class interface. The following is a simple example where no specific functionality is implemented, @@facesymbol@@‖∣

LOG4J2 Custom Appender

According to the extension of the official website, we will simply implement a appender.

Website address: http://logging.apache.org/log4j/2.x/manual/extending.html#Appenders

0. Write a custom Appender class that inherits the AbstractAppender abstract implementation class:

MyLog4j2Appender.java

/** * Custom log4j2 output source, simple output to console * @author Okong * *///here mylog4j2 corresponds to XML,/** * * <appenders> * <mylog4j2 n  Ame= "Customappender" printstring= "a staggered ape" > * </MyLog4j2> * </appenders> * */@Plugin (name = "Mylog4j2",    Category = "Core", ElementType = "Appender", PrintObject = true) public class Mylog4j2appender extends Abstractappender {   String printstring; /** * constructor can be custom parameters here directly pass in a constant and output * */protected Mylog4j2appender (String name, filter filter, layout<? e        Xtends serializable> layout,string printstring) {Super (name, filter, layout);    this.printstring = printstring;             } @Override public void append (LogEvent event) {if (event! = null && event.getmessage ()! = null) { Here the custom implementation output//Get output value: Event.getmessage (). toString ()//System.out.print (E             Vent.getmessage (). toString ()); Formatted output System.out.print (printstring + ":" + getlayout (). Toserializable (event)); }}/** receive the parameters in the configuration file * * @PluginAttribute literally know, is the attribute value of the XML node, such as <okong name= "Okong" >         </oKong> Here's name is attribute * @PluginElement: Represents an element of an XML child node, * such as * <okong name= "Okong" > * <patternlayout pattern= "[%d{hh:mm:ss:sss}] [%p]-%l-%m%n"/> * </oKong> * where, Patternlay     Out is the layout, in fact, {@link layout} implementation class.            */@PluginFactory public static Mylog4j2appender Createappender (@PluginAttribute ("name") String name, @PluginElement ("Filter") final filter filter, @PluginElement ("Layout") layout< Extends serializable> layout, @PluginAttribute ("printstring") String printstring) {if (name             = = null) {logger.error ("No Name defined in Conf.");         return null; }//default using Patternlayout if (layout = = null) {layout = Patternlayout.createdefaultlayOut ();    } return new Mylog4j2appender (name, filter, layout, printstring);        } @Override public void Start () {System.out.println ("Log4j2-start method called");    Super.start ();        } @Override public void Stop () {System.out.println ("Log4j2-stop method called");    Super.stop (); }}

A brief description of the relevant points of attention:

    • @PluginNote: This annotation is for the log4j2-spring.xml specified Appender TAG when configured later.
    • Constructors: In addition to using the parent class, you can add some of your own configuration.
    • Overriding append() method: Here the need to implement specific logic, the whereabouts of the log.
    • createAppender()Method: The primary is the log4j2-spring.xml configuration item in the receive.

1. Use a custom Appender.

log4j2-spring.xml

  <?xml version= "1.0" encoding= "UTF-8"?> <configuration status= "WARN" Monitorinterval = "+" packages= "cn.lqdev.learning" > <!--definition appenders--> <appenders> <mylog4j2 name= "Okong "Printstring=" a staggered ape (LOG4J2) "> <!--output log format--<patternlayout pattern=" [%d{hh:mm:ss:sss }] [%p]-%l-%m%n "/> </MyLog4j2> </appenders> <!--then define logger, only logger that has been defined and introduced Ppender will take effect--<loggers> <!--filter out some useless debug information for spring and MyBatis--<logger name= "ORG.SPR         Ingframework "level=" info "></logger> <logger name=" Org.mybatis "level=" info "></logger>         <!--The custom package is set to INFO, you can see that the output log does not contain the debug output--<logger name= "cn.lqdev.learning" level= "info"/> <root level= "All" > <appender-ref ref= "Okong"/> </root> </loggers> </con Figuration>  

It is important to note that, in the case of a configuration packages custom class, the package name cn.lqdev.learning will be scanned and no other method is known.

2. After starting, you can see the relevant output.

...部分省略...一枚趔趄的猿(log4j2):[14:47:43:751] [INFO] - org.apache.juli.logging.DirectJDKLog.log(DirectJDKLog.java:180) - Using a shared selector for servlet write/read一枚趔趄的猿(log4j2):[14:47:43:761] [INFO] - org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.start(TomcatEmbeddedServletContainer.java:216) - Tomcat started on port(s): 8080 (http)一枚趔趄的猿(log4j2):[14:47:43:764] [INFO] - org.springframework.boot.StartupInfoLogger.logStarted(StartupInfoLogger.java:57) - Started Chapter25Application in 2.03 seconds (JVM running for 3.164)一枚趔趄的猿(log4j2):[14:47:43:764] [INFO] - cn.lqdev.learning.springboot.chapter25.Chapter25Application.main(Chapter25Application.java:14) - Chapter25启动!

Do not know how to integrate log4j2 , you can view: The 23rd Chapter: Log Management integration of the article

Logback Custom Appender

logbackCustomizations are similar and are implemented based on a base class appender . itself logback provides AppenderBase and UnsynchronizedAppenderBase two abstract classes (synchronous and non-synchronous), so when we customize, we just need to see one of the actual business inheritance. First look at its class inheritance structure:

0. Write your custom appender class.

MyLogbackAppender.java

@Getter @setterpublic class Mylogbackappender extends unsynchronizedappenderbase<iloggingevent>{Layout<        iloggingevent> layout;            Custom Configuration String printstring; @Override public void Start () {//Here you can do some initialization judgments such as layout cannot be null, if (layout = = null) {Addwarn ("L        Ayout is not defined ");    }//or initialize the connection when writing to the database or Redis, etc. super.start (); } @Override public void Stop () {//frees related resources such as database connection, Redis thread pool, etc. System.out.println ("The Logback-stop method is tuned        Use ");        if (!isstarted ()) {return;    } super.stop (); } @Override public void append (Iloggingevent event) {if (event = = NULL | |!isstarted ()) {Retu        Rn }///Here the custom implementation output//Get output value: Event.getformattedmessage ()//System.out.print (E             Vent.getformattedmessage ());       Formatted output System.out.print (printstring + ":" + layout.dolayout (event));       }} 

It is also simple to note that the relevant points of attention:

    • startMethod: Called at the initial time. Therefore, in writing such as database storage, connection cache or MQ, you can initialize in this method.
    • stop: Called when it is stopped. You can do some resource release operations.

1. Use the custom Appender:

logback-spring.xml

<?xml version= "1.0" encoding= "UTF-8"? ><configuration debug= "false" > <!--define the storage address of the log file do not Logback The configuration uses a relative path--<property name= "Log_home" value= "/Home"/> <!--console output---<appender name= "MYLOGB Ack "class=" Cn.lqdev.learning.springboot.chapter25.config.MyLogbackAppender "> <filter class=" Ch.qos.lo        Gback.classic.filter.ThresholdFilter "> <!--Log Collection minimum log level--<level>INFO</level> </filter> <layout class= "Ch.qos.logback.classic.PatternLayout" > <!--formatting Output:%d for date,%thread for thread name,%-5level: Level shows 5 character widths from left%msg: Log messages,%n are newline characters--<pattern>%d{yyyy-mm-dd HH:mm:ss. SSS} [%thread]%-5level%logger{50}-%msg%n</pattern> </layout> <!--custom Parameters--&lt ;p rintstring> a staggered ape (logback) </printString> </appender> <!--The custom package is set to info, you can see that the output log does not contain the debug output- <logger name= "Cn.lqdev.learning "level=" info "/> <!--log output level-<root level=" info "> <appender-ref ref=" Mylogback "/&gt    ; </root> </configuration>

2. The application starts, the console output is viewed, the effect is the same:

...部分省略...一枚趔趄的猿(logback):2018-08-25 15:01:57.486 [main] INFO  org.apache.coyote.http11.Http11NioProtocol - Starting ProtocolHandler ["http-nio-8080"]一枚趔趄的猿(logback):2018-08-25 15:01:57.497 [main] INFO  org.apache.tomcat.util.net.NioSelectorPool - Using a shared selector for servlet write/read一枚趔趄的猿(logback):2018-08-25 15:01:57.520 [main] INFO  o.s.b.c.e.tomcat.TomcatEmbeddedServletContainer - Tomcat started on port(s): 8080 (http)一枚趔趄的猿(logback):2018-08-25 15:01:57.523 [main] INFO  c.l.l.springboot.chapter25.Chapter25Application - Started Chapter25Application in 54.349 seconds (JVM running for 55.377)一枚趔趄的猿(logback):2018-08-25 15:01:57.524 [main] INFO  c.l.l.springboot.chapter25.Chapter25Application - Chapter25启动!
About Shutdownhook

When you run the above customizations and appender stop the application, you will find that the defined method is stop not executed. You also need to configure a ShutdownHook system hook so that jvm it will be called before exiting.

A little knowledge

We know that in the java registration of a close hook is very simple, using the Runtime class can be, the use of the following:

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {            @Override            public void run() {                // 执行资源释放操作            }        }));

In the SpringBoot , you only need to configure it logging.register-shutdown-hook true .

logging.register-shutdown-hook=true

For the logback purposes of, it can also be logback-spring.xml configured in:

<shutdownHook class="ch.qos.logback.core.hook.DelayingShutdownHook"/>

is also possible. Or in the Startup class manually register this DelayingShutdownHook is also possible

There's a hole here, and the configuration is dead log4j2 . Google took a lap and found no solution, the online program tried again is not. It's embarrassing. If used log4j2 , it can be trickery, in the start() method, after registering the hook to call the stop method. Want to have to know the great God to share under how to solve!

Resources
    1. 78494458
    2. Http://logging.apache.org/log4j/2.x/manual/appenders.html
    3. Http://logging.apache.org/log4j/2.x/manual/extending.html#Appenders
    4. Logback.qos.ch/manual/appenders.html
    5. 75353854
Summarize

This article mainly introduces log4j2 and customizes the logback appender relevant knowledge. Implementation is relatively simple, it is important to note that when it comes to the need to close the release of related resources, you need to confirm whether there is a call before closing, otherwise it may cause the connection is not closed and other behavior, avoid unnecessary problems. about the last use of the log4j2 closed hook does not take effect, because the default is now used logback , the problem is not to delve into, but also hope to have to know the students to share the next solution! Thank you! At the same time, because there is no more than two frameworks have too much in-depth understanding, can only donuts, if the text is wrong, also hope to point out!

At last

At present, many big guys on the internet have a SpringBoot series of tutorials, if there is a similar, please forgive me. The original is not easy, the code word is not easy, but also hope that everyone support. If there is something wrong in the text, also hope to put forward, thank you.

Cliché
    • Personal QQ:499452441
    • Public Number:lqdevOps

Personal blog: http://blog.lqdev.cn

Complete Example: github.com/xie19900123/spring-boot-learning/tree/master/chapter-25

Original Address:/HTTP

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.