10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Log4j 2.0を使用してみる

Posted at

はじめに

簡単にではありますが、備忘目的でlog4j 2.0 の使用方法を記載します。
小さなJavaアプリを作成する際に使用する為、調査。

Maven依存関係定義

ライブラリ管理で利用しているMavenにlog4jを追加

pom.xml
<dependencies>
	<dependency>
		<groupId>org.apache.logging.log4j</groupId>
		<artifactId>log4j-api</artifactId>
		<version>2.10.0</version>
	</dependency>
	<dependency>
		<groupId>org.apache.logging.log4j</groupId>
		<artifactId>log4j-core</artifactId>
		<version>2.10.0</version>
	</dependency>
</dependencies>

設定ファイル作成

標準出力にログを出力するよう設定。

log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE project>
<Configuration status="off">
	<Properties>
		<Property name="format1">%d{yyyy/MM/dd HH:mm:ss.SSS} [%t] %-6p %c{10} %m%n</Property>
	</Properties>
	<Appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout>
				<pattern>${format1}</pattern>
			</PatternLayout>
		</Console>
	</Appenders>

	<Loggers>
		<Root level="trace">
			<AppenderRef ref="Console" />
		</Root>
	</Loggers>
</Configuration>

実装

ロガーの名称はlookupを使用してコピペするだけで済むようにする。

public class Hoge {
  private static final Logger logger = LogManager.getLogger(MethodHandles.lookup().lookupClass());
  
  public void sayHoge() {
    logger.info("hoge hoge");
  }
}
10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?