Spring and Logback Integration

Source: Internet
Author: User
Tags manual

The recent project used Logback as a log processing, but not very familiar with this, so write some blog record the process of learning. This blog is the first in this series.

Because I need to send email in logback, in order to facilitate testing in local eclipse, you need to install an Eclipse Email plugin, specifically refer to Mailsnag.

Logback's official website is http://logback.qos.ch/manual/configuration.html.

1. Configure the listener required for spring and Logback integration in the Web. xml file.

<context-param>
        <param-name>logbackConfigLocation</param-name>
        <param-value> classpath:log/logback.xml</param-value>
    </context-param>

    <listener>
        < Listener-class>com.npf.listener.springmvclogbackconfiglistener</listener-class>
    </listener>

2. Here we use our own springmvclogbackconfiglistener, And this listener actually inherits the Ch.qos.logback.ext.spring.web.LogbackConfigListener.

Package Com.npf.listener;

Import javax.servlet.ServletContextEvent;

Import Org.slf4j.Logger;
Import org.slf4j.LoggerFactory;
Import Org.slf4j.impl.StaticLoggerBinder;

Import Ch.qos.logback.classic.LoggerContext;
Import Ch.qos.logback.ext.spring.web.LogbackConfigListener;


public class Springmvclogbackconfiglistener extends logbackconfiglistener{
	
	private final static Logger Logger = Loggerfactory.getlogger (springmvclogbackconfiglistener.class);
	
	@Override public
	void contextinitialized (Servletcontextevent paramservletcontextevent) {
		Super.contextinitialized (paramservletcontextevent);
		Loggercontext Localloggercontext = (loggercontext) Staticloggerbinder.getsingleton (). GetLoggerFactory ();
		String SMTPHost = Localloggercontext.getproperty ("SMTPHost");
		Logger.info ("This smtphost is {}", smtphost);
	}

}

3. Configure Logback.xml, here is a small pit. There is such a configuration in Logback.xml:

<property scope= "Context" resource= "config/envspecifi.properties"/>
I was scope= "context" did not write, will always find that spring can not inject properties into the logback, very depressed. The official documents were then consulted to know:

A property can is defined for insertion in the local scope, in the context scope, or in system scope. Local scope is the default. Although it is possible to read variables from the OS environment, it's not possible to write into the OS environment.

Local scope A Property with local scope exists from the point of its definition in A configuration file until the end of I Nterpretation/execution of said configuration file. As a corollary, each time a configuration file was parsed and executed, variables in the local scope is defined anew.

CONTEXT Scope A Property with context scope is inserted to the context and lasts as long as the context or until it is C Leared. Once defined, a property in context scope is part of the context. As such, it's available in all logging events, including those sent to remote hosts via serialization.

System scope A Property with system scope was inserted into the JVM ' s system properties and lasts as long as the JVM or unt Il it is cleared.

Properties is looked up in the the The local scope first, with the context scope second, in the System Properties scope third, And in the OS environment last.
During substitution, properties is looked up with the local scope first, in the context of the scope second, in the system Propert IES scope third, and in the OS environment fourth and last.

The scope attribute of the <property> element, <define> element or the <insertFromJNDI> element can be u Sed to set the scope of a property. The scope attribute admits "local", "context" and "system" strings as possible values. If not specified, the scope was always assumed to be "local".

Please refer to the original text: http://logback.qos.ch/manual/configuration.html

Then my specific configuration is as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE logback> <configuration debug= "false" scan= "false" scanperiod= "3 seconds" > <property scope= " Context "resource=" config/envspecifi.properties "/> <appender name=" Consoleappender "class=" Ch.qos.logback.core.ConsoleAppender "> <encoder> <pattern>%date%-5level [%thread]%logger-%m%n</p attern> </encoder> </appender> <appender name= "Rollingfileappender" class= "ch.qos.logback.core.ro Lling. Rollingfileappender "> <file>${log.dir}/WebApi.log</file> <rollingpolicy class=" Ch.qos.logback.core.rolling.TimeBasedRollingPolicy "> <filenamepattern>${log.dir}/webapi-%d{yyyy-mm-dd} .%i.log </fileNamePattern> <timebasedfilenamingandtriggeringpolicy class= " Ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP "> <maxFileSize>1MB</maxFileSize> </ Timebasedfilenamingandtriggeringpolicy> </rollingPolicy> <encoder> <pattern>%date%-5level [%thread]%logger-%m%n</pattern> </encoder> &LT;/APPENDER&G
	
	T <appender name= "Accessrollingfileappender" class= "Ch.qos.logback.core.rolling.RollingFileAppender" > < file>${log.dir}/access.log</file> <rollingpolicy class= " Ch.qos.logback.core.rolling.TimeBasedRollingPolicy "> <filenamepattern>${log.dir}/access-%d{yyyy-mm-dd} .log</filenamepattern> <maxHistory>30</maxHistory> </rollingPolicy> <encoder> < Pattern>%date-%m%n</pattern> </encoder> <append>false</append> </appender> &lt ; Appender name= "Smtpappender" class= "Ch.qos.logback.classic.net.SMTPAppender" > <filter class= " Ch.qos.logback.classic.filter.LevelFilter "> <level>error</level> <onmatch>accept</on match> <onMismatch>DENY</onMismatch> </filter> <smtphost>${smtphost}</smtphost> <smtpPort>${smtpPort}</smtpPort> <to>${to}</to> <from>${from}&lt ;/from> <subject>logback test</subject> <layout class= "Ch.qos.logback.classic.html.HTMLLayout"  > <pattern>%date%level%thread%logger%message</pattern> </layout> </appender> <logger Name= "com" level= "debug" > <appender-ref ref= "rollingfileappender"/> <appender-ref ref= "AccessRollingFil Eappender "/> <appender-ref ref=" Smtpappender "/> </logger> <root level=" error "> <appender
 -ref ref= "Consoleappender"/> </root> </configuration>
4. My controller is as follows because I need to test the message, so I set the logger to error.

Package Com.npf.controller;

Import Java.util.Map;

Import Org.slf4j.Logger;
Import org.slf4j.LoggerFactory;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.beans.factory.annotation.Qualifier;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;

Import Com.npf.service.StudentService;

@Controller public
class HomeController {
	
	private final static Logger Logger = Loggerfactory.getlogger ( Homecontroller.class);
	
	@Autowired
	@Qualifier ("Studentserviceimpl")
	private studentservice studentservice;
	
	@RequestMapping (value={"/", "Home"}) public
	String showhomepage (map<string,object> Map) {
		map.put ( "Stulist", studentservice.getstudents ());
		Logger.error ("This student list is {}", studentservice.getstudents ());
		Return "Home";
	}
}

5. Start the service, visit the page and start the email Messages plugin:

The 5.1 homepage is as follows:

5.2 We received the e-mail.

Double-click to open this message.

5.3 We can find the log file of the local disk and open the view.

6. The source code used by this blog is already hosted on GitHub, and if you're interested, you can view spring and logback integration

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.