Java 滚动日志文件和删除旧的日志文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16522339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rolling log Files & removing old log files
提问by user2377755
I am working on a Java SOAP based webservice application where I am writing stdout to a text file as log for our reference. That file is growing enormously, so I need to check for the size of the file... For example if the file size crosses 10 Mb, I have to create another file.
我正在开发基于 Java SOAP 的 Web 服务应用程序,我将标准输出作为日志写入文本文件以供我们参考。该文件正在急剧增长,因此我需要检查文件的大小...例如,如果文件大小超过 10 Mb,我必须创建另一个文件。
Like this, I have to create 10 files, rotating one after the other until ten files. After reaching ten files, I have to delete the starting files and start creating again...
像这样,我必须创建 10 个文件,一个接一个地旋转直到十个文件。达到十个文件后,我必须删除起始文件并重新开始创建...
How can I delete files after the no. of files will become 10?
没有后如何删除文件?文件会变成 10 个吗?
回答by Filipe Miguel Fonseca
Most logging frameworks provide what you're looking for. In logback you should be able to achieve it by properly configuring a RollingFileAppender:
大多数日志框架都提供了您正在寻找的内容。在 logback 中,您应该能够通过正确配置 RollingFileAppender 来实现它:
RollingFileAppender extends FileAppender with the capability to rollover log files. For example, RollingFileAppender can log to a file named log.txt file and, once a certain condition is met, change its logging target to another file.
RollingFileAppender 扩展了 FileAppender,具有翻转日志文件的能力。例如,RollingFileAppender 可以将日志记录到名为 log.txt 的文件中,一旦满足某个条件,将其日志记录目标更改为另一个文件。
and
和
RollingPolicy is responsible for the rollover procedure which involves file moving and renaming.
RollingPolicy 负责涉及文件移动和重命名的翻转过程。
回答by Robert H
I use logbackto do this. The example below is a time based rolling policy. Depending upon how much data your outputting during your logs, this may work for you as-is.
我使用logback来做到这一点。下面的示例是基于时间的滚动策略。根据您在日志期间输出的数据量,这可能对您有效。
Also, as a bonus, my config file tosses the log into HTML to make it easy to view for management types who want to look though the log file.
此外,作为奖励,我的配置文件将日志转换为 HTML,以便想要查看日志文件的管理类型轻松查看。
Relevant part of the config file:
配置文件的相关部分:
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logs\logFile.html</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- daily rollover -- >
<fileNamePattern>logs\logFile.%d{yyyy-MM-dd}.%i.html</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- or whenever the file size reaches 10MB -- >
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!-- keep 10 days' worth of history -- >
<maxHistory>10</maxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<charset>UTF-8</charset>
<layout class="ch.qos.logback.classic.html.HTMLLayout">
<pattern>%d{HH:mm:ss.SSS}%thread%level%logger%line%msg</pattern>
</layout>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
relevant Maven dependancies:
相关的 Maven 依赖项:
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.0.12</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.12</version>
</dependency>
回答by tbsalling
Log4jcan do this. Specifically the RollingFileAppenderclass.
Log4j可以做到这一点。特别是RollingFileAppender类。
回答by VGR
I see a lot of answers telling you to use Log4J, but you can use Java's own logger to do this by simply creating a FileHandler:
我看到很多答案告诉您使用 Log4J,但是您可以使用 Java 自己的记录器通过简单地创建一个FileHandler来做到这一点:
Handler handler =
new FileHandler("%h/MyService-%g.log", 10 * 1024 * 1024, 10);
handler.setLevel(Level.ALL);
Logger.getLogger("").addHandler(handler);
回答by RAS
In log4j.xml you can try the following:
在 log4j.xml 中,您可以尝试以下操作:
<appender name="fileappender" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="applog.log"/>
<param name="Append" value="true" />
<param name="MaxBackupIndex" value="10"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"/>
</layout>
</appender>
The value tells log4j.xml to only keep 10 rotated log files around.
该值告诉 log4j.xml 只保留 10 个轮换的日志文件。
Alternatively, if you are using a properties file (instead of the xml)
或者,如果您使用的是属性文件(而不是 xml)
log4j.appender.File=org.apache.log4j.RollingFileAppender
log4j.appender.File.File=applog.log
log4j.appender.File.Append=true
log4j.appender.File.layout=org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c] %m%n
log4j.appender.[appenderName].MaxBackupIndex = 10
回答by EFernandes
If you use java.util.logging.Logger
, you can do it with FileHandler
.
如果您使用java.util.logging.Logger
,则可以使用FileHandler
.
Source:kodejava
来源:kodejava
package org.kodejava.example.logging;
import java.util.logging.Logger;
import java.util.logging.FileHandler;
import java.util.logging.SimpleFormatter;
import java.io.IOException;
public class RollingLogFile {
//
// Set a small log file size to demonstrate the rolling log files.
//
public static final int FILE_SIZE = 1024;
public static void main(String[] args) {
Logger logger = Logger.getLogger(RollingLogFile.class.getName());
try {
//
// Creating an instance of FileHandler with 5 logging files
// sequences.
//
FileHandler handler = new FileHandler("myapp.log", FILE_SIZE, 5, true);
handler.setFormatter(new SimpleFormatter());
logger.addHandler(handler);
logger.setUseParentHandlers(false);
} catch (IOException e) {
logger.warning("Failed to initialize logger handler.");
}
logger.info("Logging information message.");
logger.warning("Logging warning message.");
}
}