Where can i programatically find where the log4j l

2020-04-04 10:54发布

问题:

Relative paths are used in the log4j.properties file.

How can i find the absolute path programatically where logs are stored?

回答1:

From: http://www.gunith.com/2010/11/how-to-get-the-file-path-of-a-log4j-log-file/

Assume the log4j.properties file is as below,

log4j.logger.migrationlog = INFO, migration
log4j.appender.migration = org.apache.log4j.RollingFileAppender
log4j.appender.migration.File = C:/work/log/migration.log
log4j.appender.migration.MaxFileSize=20MB
log4j.appender.migration.MaxBackupIndex=1
log4j.appender.migration.layout = org.apache.log4j.PatternLayout
log4j.appender.migration.layout.conversionPattern = %d %-5p %c - %m%n

In such case, your Java code should be as follows,

Logger logger = Logger.getLogger("migrationlog"); //Defining the Logger
FileAppender appender = (FileAppender)logger.getAppender("migration");
return new File(appender.getFile());

Note that migrationlog was used to create the logger object in the first line. And migration is used to get the FileAppender which in turn calls getFile() to get the log File object.



回答2:

I think one way is like this:

since the path is relative to system property "user.dir"

so relative path = ./app.log becomes {user.dir}/app.log

get user.dir as System.getproperty("user.dir").


标签: java log4j