複数のライターを使用した Java tinylog
この Java tinylog チュートリアルでは、tinylog ライブラリを使用して、ファイルやコンソールなどの複数のライターにログ エントリを書き込む方法を学びます。
目次
<オール>tinylog の依存関係を Java プロジェクトに追加
Gradle ビルド プロジェクトで tinylog ライブラリを使用するには、次の tinylog 依存関係を build.gradle ファイルに追加します。
implementation group: 'org.tinylog', name: 'tinylog-api', version: '2.4.1'
implementation group: 'org.tinylog', name: 'tinylog-impl', version: '2.4.1'
Maven ビルド プロジェクトで tinylog ライブラリを使用するには、次の tinylog 依存関係を pom.xml ファイルに追加します。
<dependency>
<groupId>org.tinylog</groupId>
<artifactId>tinylog-api</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>org.tinylog</groupId>
<artifactId>tinylog-impl</artifactId>
<version>2.4.1</version>
</dependency>
tinylog ライブラリの詳細については、プロジェクトのホームページ attinylog.org にアクセスしてください。
tinylog を使用してエントリをログに記録する方法
まず、以下のように、tinylog API を使用していくつかのログ エントリを書き込む Java プログラムの例を作成します。
TinyLogExample.java
import org.tinylog.Logger;
public class TinyLogExample {
public static void main(String... args) {
Logger.trace("Trace message");
Logger.debug("Debug message");
Logger.info("Information message");
Logger.warn("Warning message");
Logger.error("Error message");
}
}
複数のライターにログを記録するように tinylog を構成する方法
tinylog では、tinylog.properties ファイルで複数のライターを構成して、各ライターに一意の名前を付け、名前が必ず「ライター」で始まるようにすることができます。
たとえば、次の構成では、ログ エントリをコンソールとファイル ライターの両方に書き込むことができます。
src/main/resources/tinylog.properties
writerConsole = console
writerConsole.format = {date: HH:mm:ss.SSS} {message}
writerFile = file
writerFile.format = {date: yyyy-MM-dd HH:mm:ss.SSS}{class}.{method}() {message}
writerFile.file = application.log
以下のようなコンソール出力があるアプリケーションを実行します。
01:22:30.948 Trace message
01:22:30.949 Debug message
01:22:30.949 Information message
01:22:30.950 Warning message
01:22:30.950 Error message
以下のようにログ ファイル application.log を記録します。
application.log
2022-04-07 01:22:30.948TinyLogExample.main() Trace message
2022-04-07 01:22:30.949TinyLogExample.main() Debug message
2022-04-07 01:22:30.949TinyLogExample.main() Information message
2022-04-07 01:22:30.950TinyLogExample.main() Warning message
2022-04-07 01:22:30.950TinyLogExample.main() Error message