한 줄에 Java 로깅 출력을 표시하려면 어떻게합니까?
현재 기본 항목은 다음과 같습니다.
Oct 12, 2008 9:45:18 AM myClassInfoHere
INFO: MyLogMessageHere
이 작업을 수행하려면 어떻게해야합니까?
Oct 12, 2008 9:45:18 AM myClassInfoHere - INFO: MyLogMessageHere
설명 나는 java.util.logging을 사용하고 있습니다.
Java 7부터 java.util.logging.SimpleFormatter 는 시스템 특성에서 형식 을 가져 오는 것을 지원 하므로 JVM 명령 행에 이와 같은 것을 추가하면 한 행에 인쇄됩니다.
-Djava.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'
또는 이것을 다음에 추가 할 수도 있습니다 logger.properties
.
java.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'
1) -Djava.util.logging.SimpleFormatter.format
Java 7은 java.util.Formatter
형식 문자열 구문이 있는 특성을 지원 합니다.
-Djava.util.logging.SimpleFormatter.format=...
내가 가장 좋아하는 것은 :
-Djava.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$-6s %2$s %5$s%6$s%n
출력을 다음과 같이 만듭니다.
2014-09-02 16:44:57 SEVERE org.jboss.windup.util.ZipUtil unzip: Failed to load: foo.zip
2) IDE에 넣기
IDE를 사용하면 일반적으로 프로젝트의 시스템 속성을 설정할 수 있습니다. 예를 들어 NetBeans에서 어딘가에 -D ... = ...를 추가하는 대신 작업 대화 상자에 java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-...
따옴표없이 속성을 추가하십시오 . IDE가 파악되어야합니다.
3) 그것을 Maven에두기-Surefire
편의를 위해 Surefire에 배치하는 방법은 다음과 같습니다.
<!-- Surefire -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.17</version>
<configuration>
<systemPropertyVariables>
<!-- Set JUL Formatting -->
<java.util.logging.SimpleFormatter.format>%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$-6s %2$s %5$s%6$s%n</java.util.logging.SimpleFormatter.format>
</systemPropertyVariables>
</configuration>
</plugin>
4) 수제
관련 클래스 가 거의java.util.logging
없는 라이브러리가 있습니다 . 그중에서도 그렇습니다 SingleLineFormatter
. 다운로드 가능한 항아리는 여기에 있습니다 .
public class SingleLineFormatter extends Formatter {
Date dat = new Date();
private final static String format = "{0,date} {0,time}";
private MessageFormat formatter;
private Object args[] = new Object[1];
// Line separator string. This is the value of the line.separator
// property at the moment that the SimpleFormatter was created.
//private String lineSeparator = (String) java.security.AccessController.doPrivileged(
// new sun.security.action.GetPropertyAction("line.separator"));
private String lineSeparator = "\n";
/**
* Format the given LogRecord.
* @param record the log record to be formatted.
* @return a formatted log record
*/
public synchronized String format(LogRecord record) {
StringBuilder sb = new StringBuilder();
// Minimize memory allocations here.
dat.setTime(record.getMillis());
args[0] = dat;
// Date and time
StringBuffer text = new StringBuffer();
if (formatter == null) {
formatter = new MessageFormat(format);
}
formatter.format(args, text, null);
sb.append(text);
sb.append(" ");
// Class name
if (record.getSourceClassName() != null) {
sb.append(record.getSourceClassName());
} else {
sb.append(record.getLoggerName());
}
// Method name
if (record.getSourceMethodName() != null) {
sb.append(" ");
sb.append(record.getSourceMethodName());
}
sb.append(" - "); // lineSeparator
String message = formatMessage(record);
// Level
sb.append(record.getLevel().getLocalizedName());
sb.append(": ");
// Indent - the more serious, the more indented.
//sb.append( String.format("% ""s") );
int iOffset = (1000 - record.getLevel().intValue()) / 100;
for( int i = 0; i < iOffset; i++ ){
sb.append(" ");
}
sb.append(message);
sb.append(lineSeparator);
if (record.getThrown() != null) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
record.getThrown().printStackTrace(pw);
pw.close();
sb.append(sw.toString());
} catch (Exception ex) {
}
}
return sb.toString();
}
}
Tervor와 비슷하지만 런타임에 속성을 변경하고 싶습니다.
주석에 기록 된대로 첫 번째 SimpleFormatter를 작성하기 전에이를 설정해야합니다.
System.setProperty("java.util.logging.SimpleFormatter.format",
"%1$tF %1$tT %4$s %2$s %5$s%6$s%n");
Obediah Stane이 말했듯이 자신 만의 format
방법 을 만들어야합니다 . 그러나 나는 몇 가지를 바꿀 것입니다 :
Create a subclass directly derived from
Formatter
, not fromSimpleFormatter
. TheSimpleFormatter
has nothing to add anymore.Be careful with creating a new
Date
object! You should make sure to represent the date of theLogRecord
. When creating a newDate
with the default constructor, it will represent the date and time theFormatter
processes theLogRecord
, not the date that theLogRecord
was created.
The following class can be used as formatter in a Handler
, which in turn can be added to the Logger
. Note that it ignores all class and method information available in the LogRecord
.
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
public final class LogFormatter extends Formatter {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
@Override
public String format(LogRecord record) {
StringBuilder sb = new StringBuilder();
sb.append(new Date(record.getMillis()))
.append(" ")
.append(record.getLevel().getLocalizedName())
.append(": ")
.append(formatMessage(record))
.append(LINE_SEPARATOR);
if (record.getThrown() != null) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
record.getThrown().printStackTrace(pw);
pw.close();
sb.append(sw.toString());
} catch (Exception ex) {
// ignore
}
}
return sb.toString();
}
}
This is what I'm using.
public class VerySimpleFormatter extends Formatter {
private static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
@Override
public String format(final LogRecord record) {
return String.format(
"%1$s %2$-7s %3$s\n",
new SimpleDateFormat(PATTERN).format(
new Date(record.getMillis())),
record.getLevel().getName(), formatMessage(record));
}
}
You'll get something like...
2016-08-19T17:43:14.295+09:00 INFO Hey~
2016-08-19T17:43:16.068+09:00 SEVERE Seriously?
2016-08-19T17:43:16.068+09:00 WARNING I'm warning you!!!
Per screenshot, in Eclipse select "run as" then "Run Configurations..." and add the answer from Trevor Robinson with double quotes instead of quotes. If you miss the double quotes you'll get "could not find or load main class" errors.
I've figured out a way that works. You can subclass SimpleFormatter and override the format method
public String format(LogRecord record) {
return new java.util.Date() + " " + record.getLevel() + " " + record.getMessage() + "\r\n";
}
A bit surprised at this API I would have thought that more functionality/flexibility would have been provided out of the box
This logging is specific to your application and not a general Java feature. What application(s) are you running?
It might be that this is coming from a specific logging library that you are using within your own code. If so, please post the details of which one you are using.
If you log in a web application using tomcat add:
-Djava.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter
On VM arguments
if you're using java.util.logging, then there is a configuration file that is doing this to log contents (unless you're using programmatic configuration). So, your options are
1) run post -processor that removes the line breaks
2) change the log configuration AND remove the line breaks from it. Restart your application (server) and you should be good.
'programing tip' 카테고리의 다른 글
앱 실행 실패 앱 : processDebugResources Android Studio (0) | 2020.07.18 |
---|---|
jQuery ajax 함수의 contentType과 dataType의 차이점 (0) | 2020.07.18 |
여러 개의 태그를 선택하는 XPath (0) | 2020.07.18 |
++ someVariable과 JavaScript의 someVariable ++ (0) | 2020.07.18 |
파이썬“속성”과“속성”의 차이점은 무엇입니까? (0) | 2020.07.18 |