Java programmer cultivation: Logging (1/3) and java programmer Cultivation

Source: Internet
Author: User
Tags ldap

Java programmer cultivation: Logging (1/3) and java programmer Cultivation

Preface:

As the first topic of the blog "Java programmer Cultivation", I plan to write the following three articles:

PS: the default directory is incorrect. I checked it carefully. My h1, h2, h3, and h4 are correct.

1. Origin

Writing logs in the Code is a basic and basic skill apart from implementing functions using the code. It is a required skill. But so far, there are not many articles and books on how to log.

1.1 necessity of log writing

When I encountered a bug raised by QA, I had seen two ways to reply: a) please reproduce the steps and data for me; B) Give me the logs at that time. It usually takes a lot of time to locate the problem. If it is a module developed by someone else, more time is spent. If you reply to the latter, you can quickly find the problem and start the repair process.

In terms of concept: log is a basic component of a runable and maintainable software. With logs, we can understand the real-time status of the software system during running, historical Status and exception status. A software without good logs is everyone's nightmare. Imagine the framework you are using in development, such as Spring. If there is no log, will you still use it? (Thanks to @ ix_fly for your suggestion)

If you don't want to bother yourself, you should write the logs well.

1.2 Why Logback?

There are two reasons:

However, no matter whether it is Logback, Log4j or another Log framework, some tips and suggestions on Log writing in subsequent articles are applicable.

2. the following describes how to configure Logback. It is suitable for starting configuration and getting started. It is suitable for general use. If you want to learn more, we recommend that you read the official Logback documentation and write it well. Brief Introduction to http://logback.qos.ch/manual/introduction.html2.1 Logback

In short, Log4j 1 is popular, and some problems cannot be solved. Therefore, Logback is released, which improves the performance and functions based on Log4j. However, Log4j 2 came out a few days ago. It is said that compared with Logbak, Log4j 2 has improved its performance and functionality.

2.2 about SLF4J and Logback

SLF4J(Slf4j.org), also known as Simple Logging Facade for Java, is a common logging interface. It tries to unify the world of Logging frameworks and is compatible with (Log4j 1, java. util. logging and Jakarta Commons Logging) these three most popular Logging frameworks. Logback is the default Implementation of SLF4J.

2.3 The following example shows how to import a dependency package: Logback 1.1.2 and slf4j1.7.6. Generally, you can follow the instructions below. If not, you can refer to the English document http://logback.qos.ch/setup.html. 2.3.1 General Program

Maven version

<dependency>    <groupId>ch.qos.logback</groupId>    <artifactId>logback-classic</artifactId>    <version>1.1.2</version></dependency>

Non-Maven version

Download and download http://logback.qos.ch/dist/logback-1.1.2.zip.Logback-core-1.1.2.jarAndLogback-classic-1.1.2.jarThese two Jar files areLogback-examples \ libUnderSlf4j-api-1.7.6.jarAdd these three jar files to your code package path.

2.3.2 non-independent programs

If you are using a Lib or API, you should not rely on the specific slf4j implementation. Therefore, your dependency on logback should be when running the test code. The specific implementation method is as follows:

Maven version

<dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.6</version></dependency><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>1.1.2</version><scope>test</scope></dependency>

Of course, you need to put the version information in the pom. xml file <dependencies> or <dependencyManagement>.

Non-Maven version

During the release, do not package only Logback to jar in your release program. (If you think you want to bypass it and read it again)

2.4 compatible with the legacy Logging framework

Currently, in addition to Logback, the following four types of Logging frameworks are widely used in the industry:

  • Log4j 1 (http://logging.apache.org/log4j/1.2)
  • Log4j 2 (http://logging.apache.org/log4j/2.x)
  • Java. util. logging (http://docs.oracle.com/javase/8/docs/api/java/util/logging/package-summary.html)
  • Apache commons Logging (http://commons.apache.org/proper/commons-logging)

Because Log4j 2 was just launched, its compatibility with SLF4J is unknown. SLF4J provides compatibility support for the other three frameworks. The following describes how to make Logbak compatible with these frameworks, you can also read the official note: http://www.slf4j.org/legacy.html

2.4.1 compatible with Log4j 1 and Apache Commons Logging

SLF4J supports Log4J 1 and Apache commons Logging by providing SLF4J implementation for the Log4j and Apache commons Logging interfaces. The usage is

2.4.1.1 remove references if your system directly uses the Log4j or Apache commons Logging framework, you can simply remove the references. If the third-party package you reference references Log4j or Apache commons Logging, you can use the <exclusions> label to remove references to them, as shown below:
<dependency>  <groupId>org.springframework.ldap</groupId>  <artifactId>spring-ldap-core</artifactId>  <exclusions>  <exclusion>  <artifactId>commons-logging</artifactId>  <groupId>commons-logging</groupId>  </exclusion>  </exclusions></dependency>

How to find which third-party packages reference Log4j or Apache commons Logging? There are two methods:
  • UseMvn dependency: treeCommand, as shown in, we can see that the reference to Apache commons Logging needs to be removed from org. springframework. ldap: spring-ldap-core.

  • The second method is to use the Eclipse m2e Maven plug-in. As shown in, openPom. xmlFile, selectDependency HierarchyLabel, and thenFilterInput logging or log4j in the left-sideDependency HierarchyYou can use the right-click menu to automatically filter.

2.4.1.2 Maven import the corresponding SLF4J Implementation Package

<! -- Implementation of SLF4J in Log4j --> <dependency> <groupId> org. slf4j </groupId> <artifactId> log4j-over-slf4j </artifactId> <version> 1.7.6 </version> </dependency> <! -- Implement SLF4J of Apache commons Logging --> <dependency> <groupId> org. slf4j </groupId> <artifactId> jcl-over-slf4j </artifactId> <version> 1.7.6 </version> </dependency>

2.4.1.3 import the corresponding SLF4J implementation package for non-Maven versions

Directly Delete the log4j-1. **. jar and commons-logging-1. **. jar files, download http://slf4j.org/dist/slf4j-1.7.6.zipLog4j-over-slf4j-1.7.6.jarOr (and)Jcl-over-slf4j-1.7.6.jarPut the file in classpath.

2.4.2 compatible with java. util. logging

The jul-to-slf4j module of SLF4J implements a java. util. logging handler, which converts the call to java. util. logging to the call to SLF4J implementation. Therefore, the following two steps are required:

2.4.2.1 import jul-to-slf4j module maven

<dependency><groupId>org.slf4j</groupId><artifactId>jul-to-slf4j</artifactId><version>1.7.6</version></dependency>
2.4.2.2 import jul-to-slf4j module non-Maven version

Download http://slf4j.org/dist/slf4j-1.7.6.zipto download the compressed packageJul-to-slf4j-1.7.6.jarPut it in classpath.

2.4.2.3 enable jul-to-slf4j Module

InLogging. propertiesAdd the following line:

handlers = org.slf4j.bridge.SLF4JBridgeHandler
2.5 Logback configuration file overview 2.5.1 Logback configuration file name, location, and write policy

Logback reads the configuration file in classpath in the following order. If any of the files is read, Logback stops searching.

If none of the above three files can be found in classpath, the default configuration is used. The default configuration is as follows:
  • Output Format
    %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
  • Output direction: System. out
  • Output level: Debug
In my experience, configure the Logback file according to the following policies: For Maven Projects
  • InSrc/test/resourcesDirectoryLogback-test.xmlThe log output in this configuration file is to the output to the console, the code for this application is debug level, and the other is info level.
  • InSrc/main/resourcesDirectoryLogback. xmlThe log output in this configuration file is output to the file. The file is compressed and packaged on a daily basis. The code for this application is info-level, and the other is warn-level.
For non-Maven ProjectsI have never worked on any non-Maven project in the past 10 years, so I can only talk about what I know for your reference.
  • For web projects, logback. xml is placed inWEB-INF/classesDirectory. For more information about the configuration method, see the preceding description.
  • For other projects, place them in the classpath root directory when the application starts running.
2.5.2 The Logback configuration file example describes how to write many Logback configuration files. I will not repeat them. You can search for them by yourself. Below are two I think write well, you can take a look: http://yuri-liuyu.iteye.com/blog/954038
Http://www.cnblogs.com/yongze103/archive/2012/05/05/2484753.html
Of course, the best written is the official documentation: http://logback.qos.ch/manual/introduction.html
The configuration file of the Company project is not easy to post out. below is what is used in my personal project. Some annotations are added for your reference. Logback. xml
<? Xml version = "1.0" encoding = "UTF-8"?> <Configuration scan = "true" scanPeriod = "30 seconds"> <! -- Appendar detailed explanation: http://logback.qos.ch/manual/appenders.html#RollingFileAppender --> <appender name = "FILE" class = "ch. qos. logback. core. rolling. RollingFileAppender"> <! -- Current Log file name --> <file> ldap-pwd.log </file> <rollingPolicy class = "ch. qos. logback. core. rolling. TimeBasedRollingPolicy"> <! -- Archive/ldap-pwd.2014-08-10.zip for non-current-day Log File compression backups --> <fileNamePattern> archive/ldap-pwd.1_d1_yyyy-mm-dd1_.zip </fileNamePattern> <! -- A backup file that exceeds 30 days will be deleted --> <maxHistory> 30 </maxHistory> </rollingPolicy> <layout class = "ch. qos. logback. classic. patternLayout "> <! -- Format description: http://logback.qos.ch/manual/layouts.html#ClassicPatternLayout -- & gt; <Pattern> % d [% thread] %-5 level % 40 logger {40}-% msg % n </Pattern & gt; </layout & gt; </appender & gt; <logger name = "cn. justfly. training. logging "level =" info "/> <root level =" warn "> <appender-ref =" FILE "/> </root> </configuration>
Logback-test.xml
<?xml version="1.0" encoding="UTF-8"?><configuration><appender name="Console" class="ch.qos.logback.core.ConsoleAppender"><encoder><pattern>%d [%thread] %-5level %40logger{40} - %msg%n</pattern></encoder></appender><logger name="cn.justfly.training.logging" level="debug" /><root level="info"><appender-ref ref="Console" /></root></configuration>




Write a Java program and use the while LOOP statement to calculate 1 + 1/2! + 1/3 !... 1/20! And

Well, you know the factorial. For example, 1/24 can be written as (1/2) * (1/12). a = a * (1/I) it can be understood as this. The first is 1, and the second is 1 * (1/2). The result is 0.5, that is, 0.5 * (1/3). This is equivalent to (1/2) * (1/3) is equal to the remaining order of 1/3. Are you right? I 've been following the results until now, so I can understand it. if you do not understand it, you can ask me, I am online.

How to become a programming -- increasing the value of your knowledge assets (Notes 1 For Turing programmers)

[Turing Book recommendation] The Pragmatic Programmer will be available in The English comments edition of Classical Books, Andy Hunt & David Thomas) martin Fowler & Kent Beck and other "refactoring" Martin Fowler "enterprise application architecture model" Robert Martin "Agile Software Development" (Java and C ++ description) robert Martin and his father, Agile Software Development (C #), are reviewing The article in The Pragmatic Programmer (The Pragmatic Programmer) of Andy Hunt and David Thomas. Although this book has been read for a long time, it is still an odd surprise to read it again. The author must have developed the habit of taking notes in his long-term work before he can write such a wide range of books. The book is organized by entry and has multiple entries. You can pick out one of the items you are interested in and start reading them. It is very suitable for you to read the book at dead moment (when you are idle. One of them is deeply touched and named "Your Knowledge Portfolio (Knowledge assets )". The original intention of Portfolio here refers to the investment Portfolio. For example, if you have some money, save some money in the bank, buy some stocks, buy some funds, buy some real estate, and buy some insurance. In short, do not put all your eggs in one basket to reduce risks and increase value. The author proposed the business path:-Invest Regularly, continuous investment, and accumulation. -- Diversity: expands knowledge, diversify, reduces risks, and increases potential. -- Manage Risk: controls risks. In response to this, you must combine short-term and long-term learning technologies. -- Buy low, Buy hign, low Buy high sell, looking for potential stocks. -- Review and rebalance. These do not need to be explained too much in the Age of nationwide fund buying and stock trading. The eight goals proposed by the author may be more practical: learning a new language every year. Different languages can solve the same problem in different ways. By learning different methods, we can broaden our thinking and break the limitations of our thinking. Learning different languages will change and enrich the way you think about problems. Moreover, it is much easier to learn new languages than in the past. Compilers, development environments, and documents can all be found online. If you are familiar with static languages, try dynamic languages. Java programmers prefer Ruby, Groovy, and JavaScript. Programmers developed on Windows can try Microsoft PowerShell; for Web development, you can choose PHP and Ruby. For game development, you can choose Lua. In addition, Python is an option that deserves careful consideration. Of course, there is also the switching of the programming paradigm, from process to object-oriented, from object-oriented to functional (a good choice is the Erlang of the concurrency era) and logic (represented by Prolog ). -- Read a technical book every quarter. Read one copy every month after you get used to it. Similarly, the reading interest should be wider and diversified. -- Read non-technical books. Don't forget that software is used by people. Learn more about people. -- Participate in technical courses. It can be a school, a training course, or a technical meeting. -- Join a local programmer organization. We should not only listen with ears, but also actively participate. "Isolation is critical to your career ." Discover friends outside of the company. -- Experiment in different environments. If you only use Windows at work, use Unix/Linux at home. If you only use makefile and editor, try IDE or vice versa. -- Keep pace with the times and subscribe to industry magazines. -- Surfing the Internet, reading valuable articles and websites ...... The last article is now becoming more and more important and has largely replaced the previous one. Many mainstream foreign technology magazines are now fully open to the Internet, including the book's recommended Dr. Dobb's... 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.