简体   繁体   中英

How can I print the log4j output into a log file?

I am pretty new in log4j and I have the following problem.

Into a simple Java application I am using log4j that actually correctly print the logging output into the console (the shell), I am using this configuration into the log4j.properties file:

# Define the root logger with appender X:
log4j.rootLogger = DEBUG, consoleAppender

## Set the appender named X to be a console appender:
log4j.appender.consoleAppender = org.apache.log4j.ConsoleAppender

# Define the layout for console Appender appender
log4j.appender.consoleAppender.layout = org.apache.log4j.PatternLayout
log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

It works fine but I need to do the following things:

  1. Instead print the logging output into the console I want that it is written inside a mylog.log file. How can I do it?

  2. Actually the logging line have the following shape:

     21406 [main] DEBUG utility.Mailer - (mailer) MESSAGGIO INVIATO 

    what exactly represent the 21406 string at the beginning of this logging line? How can I print the current date and time at the beginning of the logging line?

Tnx

You need to add a file appender to your log4j config file

Eg :

log4j.appender.FILE.File=D:/logs/file.log
log4j.appender.FILE.layout=org.apache.log4j.TTCCLayout
log4j.appender.FILE.layout.ContextPrinting=true
log4j.appender.FILE.Threshold=DEBUG

You need a file appender, in addition to your stdout (console) appender. Of course, you should probably use the same pattern you use for your console. One such example would be:

log4j.rootLogger = INFO, stdout, R

log4j.appender.R = org.apache.log4j.RollingFileAppender
log4j.appender.R.layout = org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern = %d %5p [%t] (%F <<%M>>\:%L) - %m%n
log4j.appender.R.File = /var/www/porject-name/www/logs/project-name.log
log4j.appender.R.MaxFileSize = 100000KB
log4j.appender.R.MaxBackupIndex = 10

Re. 1 As Salah and Schaka suggested - you need to define a file appender.

Re. 2 In your console appender you've defined a pattern that starts with %-4r where r means:

Used to output the number of milliseconds elapsed from the construction of the layout until the creation of the logging event.

and the -4 part means "right padding if less than 4 digits". To display current date and time use %d pattern.

Source: PatternLayout JavaDoc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM