Java application log

frankiegao123 taro Road Source

 

Log in applications is very, very important, a good log information can help us to quickly locate when the program BUG, ​​and to find out why.

 

However, many places have adopted logs introduce AOP as introduced, in fact, cut the log to be used, then it is extremely unscientific! For the log, it is only the beginning of the method, the end of the abnormal output something, it is absolutely not enough, so the logs for log analysis does not make any sense. If the start and end of the entire log method, and that method it? If the method does not log, then it completely lost its meaning log! If the application you want to find problems caused by what the cause, there is no effect. This log might as well do not!

 

Developers hope so as to allow the application of this article can be more emphasis on the log, can be meaningful in the application log output.

 

The basic format of the log

 

Mainly in the log output file should include the following:

 

  • time

  • The main use of the log level

  • Call chain identification (optional)

  • Thread name

  • Logger name

  • Log content

  • Exception stack (not necessarily)

 

11 : 44 : 44.827 WARN [93ef3E0120160803114444- 1.2 ] [main] [ClassPathXmlApplicationContext] Exception encountered during context initialization - cancelling refresh attempt

 

Log Time

 

As the date and time of the log generated, this data is very important in general to the millisecond. As the general by-day rolling log file, the date does not need to put this time using HH: mm: ss.SSS format can be.

 

Log Level

 

The main use of the log level DEBUG, INFO, WARN, ERROR.

 

DEBUG

The content output DEUBG level debugging nature, the level of the log mainly for the development, testing phase output. This level of logging should be as detailed and facilitate the development, testing phase problems or abnormal, be analyzed.

 

INFO

The content of the output INFO level prompted the nature of the level of the log mainly for logging output production environment. The level or higher log do not appear in the loop, you can start or end times of the output cycle, as well as other important data in the cycle.

 

  • Application startup configuration parameter values ​​loaded (example: connection parameter, the parameter thread pool, timeout, etc., as well as some related environment configuration, or the entire configuration parameter)

  • Some important class name of the object dependency injection

  • When the process (service method) input parameter values, return values, since some methods into the reference value is very large, it once output at the entrance, inside the service or call the non-serving methods do not need to output

  • Method important part, such as: the more important data acquired from the database, and the input parameter value and the third party interface to call the return value of the interface

 

INFO level log is in principle a production environment, through INFO and higher-level log, you can understand the system operating conditions, and when problems or abnormal, problems can quickly locate, restore context data at the time of the call, can be heavy now the issue.

 

It recommended that the project is completed, in a test environment into a log level INFO, and then see if the situation can understand the use of the information by the application of INFO level, whether these logs can provide useful information to troubleshoot the problem if a problem occurs.

 

WARN

The main level warning output WARN nature of the content that is predictable and there is a plan, for example, a method is empty or the value of the parameter does not satisfy the conditions of the process operating parameters. In the WARN level of output should be more detailed information to the log analysis after the event, do not write directly to:

 

Bad log

log.warn( "name is null" );

 

In addition to the output of reasons for the warning, but also other parameters we need to be content output in order to have more information for reference log analysis.

 

Recommended log

log.warn( "[{}] name is null, ignore the method, arg0: {}, arg1: {}" , methodName , arg0 , arg1 );

 

ERROR

ERROR level mainly directed to some of unpredictable information, such as: error, abnormality, for example, network traffic captured in the catch block, the database connection abnormality such as abnormal if little effect on the overall process system, logging level may be used WARN output. When the output of the ERROR logging level, as much as possible into the parameter output method, the object execution method and the like during the data generated with errors, when the data of the exception object, the object needs to be output together in:

 

Recommended log

log.error( "Invoking com.service.UserService cause error, username: {}" , username , e );

 

Do not write (hereinafter, this content will log e as a parameter, the effect of using e.toString () consistent output without exception stack):

 

Bad log

log.error( "Invoking com.service.UserService cause error, username: {}, e: {}" , username , e );

 

Do not output this log in the log below, in the execution stack itself will output the contents of the e e.getMessage, no need to export it again in the log line, such a log to track problem is meaningless!

 

Bad log

log.error( e.getMessage() , e );

 

Call chain logo

 

In a distributed application, a user may request a number of service calls completed, these services may still be nested calls, thus completing a request does not log in the log file an application, but dispersed nodes in different applications on different servers the log file. This identification is connected in series to a call log in the entire system requests.

 

Call chain identification format:

 

  • A unique string (trace ID)

  • Call hierarchy (span ID)

 

Call chain logo as an option, not only when the output data []can be.

 

Thread name

 

This log output thread, typically in one application a synchronization request is completed by the same thread, the thread name output can be classified in each request generated log, the log facilitates to distinguish the current request context.

 

Logger name

 

Logger name commonly used class name, the log file can be output in a simple class name, to see whether the actual situation need to use the package name. Log saw is mainly used to find the class to which the log output to locate the problem.

 

Log content

 

Precautions

 

Disable System.out.println

src / main code prohibited the use System.out.println output because production is generally not the standard output and error to redirect the output to a file, if the code used in the output log way, could result in the loss of output .

 

Alternatively spliced ​​varying parameter log

The use slf4j Logger processed using a reference variable which log output function, a character string not to be spliced ​​in the log, such as:

 

Recommended log

log.debug( "Load No.{} object, {}" , i , object );

 

Do not write log.debug ( "Load No." + i + " object, " + object );this is because when the log level INFO or raised above the level, this will increase the string concatenation fearless.

 

Implement toString ()

Required output target log, toString method should be fast in its class, so as to output only the object class name and hashCode when the log output. The method toString class should handle all the fields. toString method toString function may be generated by the automatic features of the IDE. toString method is not recommended toString generated by reflection or some tools, and do not directly use the sequence JSON JSON string into tool, both of which are processed using reflection, only the output log more impact application performance.

 

Prevention null pointer

Do not call the object's method in the log acquisition value, unless the object is to ensure that certainly is not null, or is likely because of problems caused by the application logs generated a null pointer exception.

 

Bad log

log.debug( "Load student(id={}), name: {}" , id , student.getName() );

 

It can be changed (when the student is null, so that it does not produce a null pointer exception):

 

Recommended log

log.debug( "Load student(id={}), student: {}" , id , student );

 

Analyzing some necessarily be spliced ​​string, or require time-consuming, waste of memory to produce contents of the log as the log output, use log.isXxxxxEnable () before splicing process, such as:

 

Recommended Code

if ( log.isDebugEnable() ) {
    StringBuilder builder = new StringBuilder();
    for ( Student student : students ) {
        builder.append( "student: " ).append( student );
    }
    builder.append( "value: " ).append( JSON.toJSONString(object) );
    log.debug( "debug log example, detail: {}" , builder );
}

 

information security

 

Remember not to log passwords and personal information related to the content! To facilitate positioning problems, the following is most relaxed when sensitive information is directed to the log output (data in plain text only less, not more) requirements:

 

Types of
Claim
Examples
Explanation
password
No output
******
Login password, and other types of payment password password
Credit Card CVV2
No output
***
 
Credit card validity
No output
****
 
Verification code
No output
******
Captcha code, SMS verification code, PIN mailers, etc.
Key, salt
No output
******
A key encryption algorithm, the message digest of the public and private key salts, and the digital signature and the signature verification algorithm used, etc.

Session ID

Device fingerprinting (ID)

Fingerprint token

The ciphertext data

Front 55
7SuA8***TtslB

There are the following types:

1. The application session identifier, such as: Web, APP, H5 and other state information for identifying the session identifier

Device or device ID 2. APP fingerprint identification device

token 3. APP for fingerprint authentication

4. ciphertext data refers to data encryption

Masked characters no matter how many bits are output 3 *

Bank card number
After the first 6 4
622666******0831 Bank card number up to 19 digits
phone number
First 3 4
137****9574 11-digit fixed length
ID number
1 before after 1
3******X
Fixed-length 18
Full name
Hidden surname
* Shiren
The surname Hide
IP addresses
1 before after 1
10.*.*.27
Hide IP address of paragraphs 2, 3
email address
1 before after 1
w**[email protected] Prior to the mailbox name @ only mask the mask part no matter how many bits are output ***
address
Hidden number
Tibet North Road, Shanghai *** *** *** Room Floor
 

Said column portion extracting only the data display request, other display principle can not know the original data by the data mask.

 

Masks realized as tools, reference: https: //github.com/frankiegao123/mask-utils

 

The exception stack

 

异常堆栈一般会出现在 ERROR 或者 WARN 级别的日志中,异常堆栈含有方法调用链的系统,以及异常产生的根源。异常堆栈的日志属于上一行日志的,在日志收集时需要将其划至上一行中。

 

日志文件

 

日志文件放置于固定的目录中,按照一定的模板进行命名,推荐的日志文件名称:

 

  • 当前正在写入的日志文件名:<应用名>[-<功能名>].log

  • 已经滚入历史的日志文件名:<应用名>[-<功能名>].log.<yyyy-MM-dd>

     

 

日志配置

 

输出

 

根据不同的环境配置不同的日志输出方式:

 

  • 本地调试可以将日志输出到控制台上

  • 测试环境或者生产环境输出到文件中,每天产生一个文件,如果日志量庞大可以每个小时产生一个日志文件

  • 生产环境中的文件输出,可以考虑使用异步文件输出,该种方式日志并不会马上刷新到文件中去,会产生日志延时,在停止应用时可能会导致一些还在内存中的日志未能及时刷新到文件中去而产生丢失,如果对于应用的要求并不是非常高的话,可暂不考虑异步日志

 

logback 日志工具可以在日志文件滚动后将前一文件进行压缩,以减少磁盘空间占用,若使用 logback 对于日志量庞大的应用建议开启该功能。

Guess you like

Origin www.cnblogs.com/xiang--liu/p/11597404.html