java Gradle 日志输出级别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26635671/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:17:32  来源:igfitidea点击:

Gradle Logging Output Levels

javalogginggradle

提问by SS44

In my project classes I've used java.util.logging.Loggerand added various log output's throughout my code, using various log levels ie.

在我的项目类中,我在java.util.logging.Logger整个代码中使用并添加了各种日志输出,使用各种日志级别,即。

src/main/java/Run.java

src/main/java/Run.java

import java.util.logging.Level;
import java.util.logging.Logger;

public class Run{


    public static void main( String args[] ){
      System.out.println("Hello World");

      logger.log(Level.CONFIG, "Just some config info");
      Logger logger = Logger.getLogger(Run.class.getName());
      logger.log(Level.INFO, "Just logging some info");
      logger.log(Level.FINE, "Fine logging");
      logger.log(Level.FINER, "Finer logging");
      logger.log(Level.WARNING, "This is a warning log!");

    }
}

Currently when I run gradle -i testall log messages with the Level.INFOdefined are shown but none of the config, warn or fine messages are output.

目前,当我运行gradle -i test所有带有Level.INFO定义的日志消息时,显示但没有输出配置、警告或罚款消息。

I've tried updating my build.gradlefile such that:

我试过更新我的build.gradle文件,这样:

apply plugin: 'java'
apply plugin:'application'
mainClassName = "Run"

repositories {
    mavenCentral()
}

dependencies {
    testCompile "junit:junit:4.11"
}

run{
    systemProperties = ['java.util.logging.config.file' : 'logging.properties']
}

I've included:

我已经包括:

systemProperties = ['java.util.logging.config.file' : 'logging.properties']

Then created /src/main/resource/logging.propertiess

然后创建/src/main/resource/logging.propertiess

handlers= java.util.logging.ConsoleHandler
.level= CONFIG
java.util.logging.ConsoleHandler.level = FINER
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

Running:

跑步:

gradle run

I get:

我得到:

:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:run
Hello World

BUILD SUCCESSFUL

And when running gradle -i runI get: Successfully started process 'command '/Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/bin/java'' Hello World :run (Thread[main,5,main]) completed. Took 0.202 secs.

当运行gradle -i run我得到: 成功启动进程 'command '/Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/bin/java'' Hello World :run (Thread[main,5,主要])完成。耗时 0.202 秒。

BUILD SUCCESSFUL

ie. no logging information. However commenting out the system.properties from within the run task and re-running gradle -i runI get:

IE。没有日志信息。但是从运行任务中注释掉 system.properties 并重新运行gradle -i run我得到:

Successfully started process 'command '/Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/bin/java''
Hello World
Nov 05, 2014 12:07:42 PM Run main
INFO: Just logging some info
Nov 05, 2014 12:07:42 PM Run main
WARNING: This is a warning log!
:run (Thread[main,5,main]) completed. Took 0.229 secs.

BUILD SUCCESSFUL

The info and warning level logs, but not the fine or finer ones.

信息和警告级别记录,但不是罚款或更精细的。

tldr;

tldr;

How do I get the config, fine & finer level logs to log to the console in a generic gradle java project ?

如何在通用 gradle java 项目中获取配置、精细和更精细级别的日志以登录到控制台?

回答by jalopaba

Several options (I personally prefer option 2.2):

几个选项(我个人更喜欢选项 2.2):

1) Custom logging.properties file:

1) 自定义 logging.properties 文件:

The Java Logging API has a default logging configuration file at <JRE_HOME>/lib/logging.properties. You can use your own config file setting the JVM property java.util.logging.config.file.

Java Logging API 有一个默认的日志配置文件,位于<JRE_HOME>/lib/logging.properties. 您可以使用自己的配置文件设置 JVM 属性java.util.logging.config.file

handlers = java.util.logging.ConsoleHandler

Run.handlers = java.util.logging.ConsoleHandler
Run.level = FINER
Run.useParentHandlers = false

java.util.logging.ConsoleHandler.level = ALL
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

You have to set useParentHandlers = falseto avoid getting duplicate prints from parent handlers.

您必须设置useParentHandlers = false以避免从父处理程序获得重复打印。

1.1) Set above property with absolute path

1.1) 使用绝对路径设置上述属性

Did not even try ;-)

甚至没有尝试;-)

1.2) Load custom file as follows in Run.java

1.2)加载自定义文件如下 Run.java

Loading it as follows in Run.java:

加载如下Run.java

    InputStream inputStream = Run.class.getResourceAsStream("mylogging.properties");
    try {
        LogManager.getLogManager().readConfiguration(inputStream);
    } catch(Exception e) {
        e.printStackTrace();
    }

2) Custom system property (i.e.: logLevel)

2)自定义系统属性(即:logLevel

Define a systemPropertyin your build.gradle:

定义systemProperty你的build.gradle

run {
    systemProperty 'logLevel', System.getProperty('logLevel')
}

Add a defaultLogLevelin Run.java:

添加defaultLogLevelRun.java

public static Level defaultLevel = Level.INFO;

Get the value of logLevelproperty:

获取logLevel属性值:

String logLevel = System.getProperty("logLevel");

And set the defined level in logger:

并在记录器中设置定义的级别:

Logger logger = Logger.getLogger(Run.class.getName());
logger.setLevel(logLevel.isEmpty() ? defaultLevel : Level.parse(logLevel));

2.1) Create a new ConsoleHandlerand switch-off print from parent handlers

2.1)ConsoleHandler从父处理程序创建一个新的和关闭的打印

    System.out.println(Run.class.getName());
    Logger logger = Logger.getLogger(Run.class.getName());
    logger.setLevel(logLevel.isEmpty() ? defaultLevel : Level.parse(logLevel));

    Handler consoleHandler = new ConsoleHandler();
    consoleHandler.setLevel(logLevel.isEmpty() ? defaultLevel : Level.parse(logLevel));
    logger.addHandler(consoleHandler);

    logger.setUseParentHandlers(false);

2.2) Find parent ConsoleHandlerand set defined level

2.2) 找到父ConsoleHandler级并设置定义的级别

    Logger topLogger = Logger.getLogger("");

    Handler consoleHandler = null;
    for (Handler handler : topLogger.getHandlers()) {
        if (handler instanceof ConsoleHandler) {
            //found the console handler
            consoleHandler = handler;
            break;
        }
    }

    if (consoleHandler == null) {
        // not found, create a new one
        consoleHandler = new ConsoleHandler();
        topLogger.addHandler(consoleHandler);
    }
    //set the console handler level
    consoleHandler.setLevel(logLevel.isEmpty() ? defaultLevel : Level.parse(logLevel));

With that, gradle runyields messages above the default level (INFO). With

这样,gradle run产生高于默认级别(INFO)的消息。和

gradle run -DlogLevel=FINE

you can control which messages are shown.

您可以控制显示哪些消息。