log4j2は、PatternLayoutメカニズムを介してログセンシティブフィールドの感度低下を実現します

1.まず、正規表現を理解します:。*、。*?、。+?マッチング方法

public static void main(String[] args) {
        String content ="hello world";
        String param1 = ".*";
        String param2 = "hell.*?o";
        String param3 = "hel.+?l";

        Pattern p1 = Pattern.compile(param1);
        Pattern p2 = Pattern.compile(param2);
        Pattern p3 = Pattern.compile(param3);
        Matcher m1 = p1.matcher(content);
        if (m1.find()){
            for (int i = 0; i <=m1.groupCount() ; i++) {
                System.out.println("p1--------------"+m1.group(i));
            }
        }
        Matcher m2 = p2.matcher(content);
        if (m2.find()){
            for (int i = 0; i <=m2.groupCount() ; i++) {
                System.out.println("p2--------------"+m2.group(i));
            }
        }
        Matcher m3 = p3.matcher(content);
        if (m3.find()){
            for (int i = 0; i <=m3.groupCount() ; i++) {
                System.out.println("p3--------------"+m3.group(i));
            }
        }

    }

実装の結果は次のとおりです。

p1--------------hello world
p2--------------hello
p3--------------hello worl

次の要約を描くことができます。

。*:すべてのコンテンツに一致します。「h。* d」の場合、出力は「hello world」. なります*これ、改行文字\ n以外の任意の1文字に一致すること意味します

hell。*?o「hell」の先頭から「o」が最初に表示れる位置までコンテンツを一致させます。「?」を追加すると、レイジーモードを意味します。これは、任意の回数の繰り返しに一致することを意味しますが、全体が一致することを前提としています。成功する可能性があります最小限の繰り返しを使用します。

hel。+?l「hel」の先頭から「l」の最後の位置までのコンテンツを一致させます

2.上記のマッチングメカニズムを理解した後、log4jxmlファイルで機密リソースの置換と感度低下を構成できます。

<!--  PatternLayout的pattern配置 

     %replace{%replace{[%m]}{"passwd":".*?"}{"passwd":"***"}}{"account":".*?"}{"account":"***"}

     这一段为替换规则,达到的效果是按照正则匹配把json报文中的"passwd":"778password"和"account":"778account"替换为"passwd":"***"和"account":"***"

     正则表达式根据需求自己定义

-->

<property name="test">

 <![CDATA[ [%-5level][%d{yyyy-MM-dd HH:mm:ss,SSS}][%t][%c][%X{busi_seq}][%X{sys_seq}][%C{1}:%L]: %replace{%replace{[%m]}{"passwd":".*?"}{"passwd":"***"}}{"account":".*?"}{"account":"***"}%n ]]>

</property>

最終的に、ログの「passwd」フィールドと「account」フィールドのデータ値は「********」に置き換えられます

おすすめ

転載: blog.csdn.net/u013804636/article/details/107320761