Java log printing essentials

  log4j, logging, slf4j

Basic concept

  • Log4j Three Pieces

  • Log level

Logger for packages and classes

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



  • ConsoleAppender

  • FileAppender

    • RollingFileAppender

    • RandomAccessFileAppender

  • Messaging

    • JMSAppender

    • SMTPAppender

  • DB

    • JDBCAppender

    • JPAAppender

    • NoSQLAppender

  • Remote

    • SocketAppender

    • SyslogAppender


  • 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
#Redirect to Tomcat logs folder #log4j.appender.file.File=${catalina.home}/logs/logging.log   
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

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


  • 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