logback系列之二:输出日志到文件

logback系列之一:输出日志到控制台
logback系列之二:输出日志到文件
logback系列之三:输出日志到文件(滚动)
logback系列之四:输出日志到不同文件


logback系列之一:输出日志到控制台类似,改动的地方:

1. logback[-test].xml文件:
<appender name="fileAppender" class="ch.qos.logback.core.FileAppender">
    <file>/logs/granularity.log</file>
    <encoder><!-- 必须指定,否则不会往文件输出内容 -->
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n</pattern>
    </encoder>
    <append>true</append>
    <prudent>false</prudent>
</appender>

<root level="DEBUG">
    <appender-ref ref="fileAppender" />
</root>


调用测试类的方法,生成granularity.log文件。

附:
①. prudent:小心的,慎重的。如果设置为true,不同JVM的file appenders能够安全地将日志输出到同一个文件中。
    这是通过锁定文件通道实现的:

  protected void writeOut(E event) throws IOException {
    if (prudent) {
      safeWrite(event);
    } else {
      super.writeOut(event);
    }
  }

  private void safeWrite(E event) throws IOException {
    ResilientFileOutputStream resilientFOS = (ResilientFileOutputStream) getOutputStream();
    FileChannel fileChannel = resilientFOS.getChannel();
    if (fileChannel == null) {
      return;
    }
    FileLock fileLock = null;
    try {
      fileLock = fileChannel.lock(); // 加锁
      long position = fileChannel.position();
      long size = fileChannel.size();
      if (size != position) {
        fileChannel.position(size);
      }
      super.writeOut(event);
    } finally {
      if (fileLock != null) {
        fileLock.release(); // 释放锁
      }
    }
  }


②. 当prudent为true时,如果append设置为false,会被强行转成true。
    这是在start方法中处理的:

  if (prudent) {
    if (!isAppend()) {
      setAppend(true);
      addWarn("Setting \"Append\" property to true on account of \"Prudent\" mode");
    }
  }

猜你喜欢

转载自czj4451.iteye.com/blog/1975220