Permissions on log files created by log4j RollingFileAppender

不羁的心 提交于 2019-11-27 22:04:49

File permissions are determined by the user's umask - there's not a way to change it in log4j itself.

You probably want to set the user's umask to 0117

$ umask -S 0117
u=rw,g=rw,o=

Log4J-core-2.9 will provide this feature fileOwner, fileGroup and filePermissions for posix OS in FileAppender, RollingFileAppender and RollingRandomAccessFileManager:

<RollingFile name="RollingFile"
             fileName="mylogs.log"
             filePattern="mylogs-$${date:MM-dd-yyyy}-%i.log.7z"
             fileOwner="log4j"
             fileGroup="log4grp"
             filePermissions="rw-r-----">

I realize this is an old question, but since it was the first hit still when I searched for this problem...

You can simply subclass RollingFileAppender and set the permission on the file when it is first opened, like this:

public class WorldWritableFileAppender extends RollingFileAppender {
    @Override
    public synchronized void setFile(String fileName, boolean append,
            boolean bufferedIO, int bufferSize) throws IOException {
        super.setFile(fileName, append, bufferedIO, bufferSize);
        File f = new File(fileName);
        if(f.exists()) {
            java.nio.file.Files.setPosixFilePermissions(f.toPath(), 
                    EnumSet.allOf(PosixFilePermission.class));
        }
    }
}

Then just reference WorldWritableFileAppender instead of RollingFileAppender in your log4j.xml.

<appender name="name" class="path.to.WorldWritableFileAppender">

This works because setFile() is called both when originally setting up the logger, and when creating a new file after rollover. The old file is moved aside with File.renameTo(), which preserves the permissions.

inside log4j.properties include this: log4j.appender.file.File=${user.home}/log anyway, this is my configuration that show info in console and file "log".

# Root logger option
log4j.rootLogger=DEBUG, stdout, file

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=${user.home}/test
log4j.appender.file.MaxFileSize=5MB
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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!