0
0

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 1 year has passed since last update.

Lombokを利用したしたログ出力でMaskをしたい、またはログ出力させない

Last updated at Posted at 2023-09-16

やりたいこと

  1. ログ出力時にマスクを掛けて機密情報を出力しない
  2. ログ出力時にそもそもログを出力させない

環境

  • Java 17
  • lombok 1.18.28

Maskを掛けない場合

ログ出力対象のユーザークラスを作成し、@Dataアノテーションを付与

User.java
import lombok.Data;
import lombok.ToString;

@Data
public class UserInfo {

	private String userId;
	
	private String password;
	
	private String mail;	
}

ログ出力

var userInfo = new UserInfo();
userInfo.setUserId("user1234");
userInfo.setPassword("password");
userInfo.setMail("user123@gmail.com");
		
log.info(userInfo.toString());

ログ出力結果

パスワードがそのまま出力される

UserInfo(userId=user1234, password=password, mail=user123@gmail.com)

@ToString.Includeを指定

@ToString.Includeを付与することで、getterの戻り値をtoString()で出力できるようになる

  • Maskを行いたいメンバー変数のgetterに@ToString.Includeを付与する
  • name属性にメンバー変数と同じ名前を指定する

getter名をgetPasswordにするとMaskされた値しか取れなくなるので注意

User.java
import lombok.Data;
import lombok.ToString;

@Data
public class UserInfo {

	private String userId;
	
	private String password;
	
	private String mail;

	@ToString.Include(name = "password")
	public String getMaskPassword() {
		return "***";
	}
}

ログ出力結果

ログにMaskがかかっている

UserInfo(userId=user1234, mail=user123@gmail.com, password=***)

getPassword()を呼べばMaskがかかっていない値が取得可能

log.info(userInfo.getPassword()); // password

@ToString.Excludeを指定

Maskを掛けるのではなくてログ出力させたくない場合は@ToString.Excludeを付与する

  • Maskを行いたいメンバー変数に@ToString.Excludeを付与する
User.java
import lombok.Data;
import lombok.ToString;

@Data
public class UserInfo {

	private String userId;
	
	@ToString.Exclude
	private String password;
	
	private String mail;
}

ログ出力結果

passwordの項目自体がログ出力されない

UserInfo(userId=user1234, mail=user123@gmail.com)
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?