Java log printing essentials

  log4j, logging, slf4j

Basic concept

  • Log4j Three Pieces
    logger、appender、layout

  • Log level
    ALL<TRACE<DEBUG<INFO<WARN<ERROR<FATAL<OFF

Logger for packages and classes

  • log4j.logger.<PACKAGE_NAME>=<LEVEL>

  • log4j.logger.<PACKAGE_NAME>.<CLASS_NAME>=<LEVEL>, <LOGGER_NAME>

appender

  • ConsoleAppender

  • FileAppender

    • RollingFileAppender

    • RandomAccessFileAppender

  • Messaging

    • JMSAppender

    • SMTPAppender

  • DB

    • JDBCAppender

    • JPAAppender

    • NoSQLAppender

  • Remote

    • SocketAppender

    • SyslogAppender

layout

  • PatternLayout

  • HTMLLayout

  • XMLLayout

  • JSONLayout

  • SerializedLayout

Rolling file sets the reserved file size (Can be used in a test environment to avoid log accumulation occupying disk space)

# Root logger option 
log4j.rootLogger=INFO, file   
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender   
#Redirect to Tomcat logs folder #log4j.appender.file.File=${catalina.home}/logs/logging.log   
log4j.appender.file.File=C:\\logigng.log 
log4j.appender.file.MaxFileSize=10MB 
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Pattern layout parameter description

  • %d{ABSOLUTE}
    Printing time; ABSOLUTE is in HH:mm:ss,SSS format.

  • %5p
    Print log level (ERROR, DEBUG, INFO, etc.); Those less than 5 characters are filled with spaces.

  • %t
    Print thread name

  • %c{1}
    Print class and package name (only the first layer is shown);

  • %M
    Print method name

  • %L
    Print line number

  • %m
    Messages to be printed

  • %n
    Wrap

  • %highlight{pattern}{style}
    Adds ANSI colors to those that conform to the specified format

Anti-pattern

  • Repeat log, such as the exception of dao layer thrown out, also log

  • Log still uses line breaks

  • Log too many things, too long

  • Log should be used in test, and assert should be more appropriate.

  • The exception did not log out.

  • Use non-uniform formats such as # # #

  • Print confidential information such as account and password

Best practices

  • Print timestamp, thread name, class name, serial number, user id

  • Use rolling appender+maxFileSize and maxBackupIndex

  • Print exception Remember to print the stack

  • Do not print extra things in production environment

  • Use parameterization to avoid string concatenation

  • Logback or log4j2 removes enabled judgment

  • Static final modification

  • Log level should be determined well.

  • The value of the print context

  • Do not print security information such as user name and password

  • Pay attention to the system disk space+regular cleaning policy