Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.
preface
- In the project online environment, you need to record various error information, status information, debugging information, and execution time records generated during program running. It can be used to locate problems, locate data, and so on.
- Log specific implementation can be log4J and Logback, and here we use SLF4J as the implementation of the log system.
Use SLF4J
- Using the IDEA tool, you can install the Lombok plug-in and import the Maven package:
< the dependency > < groupId > org. Projectlombok < / groupId > < artifactId > lombok < / artifactId > < version > 1.18.4 < / version > </dependency>Copy the code
- Add the @slf4J annotation to the class that needs to print logs. If you look at the compiled class file, you will see that the @slf4j annotation is encoded as follows:
public static final Logger log = LoggerFactory.getLogger(TestLog.class);
Copy the code
- To print logs, use the following methods:
/** * @Author: ZRH * @Date: 2021/9/27 17:25 */ @Slf4j public class TestLog { //public static final Logger log = LoggerFactory.getLogger(TestLog.class); public static void main (String[] args) { Map<String, String> params = new HashMap<>(); Params. Put (" Phones ", "13668200646152222222156852699"); params.put("timestamp", "1231"); Params. Put ("NAME", "zhang SAN "); Params. Put (" id ", "150303195208077885150031520071 X 58, 15030319520807908 X"); String phone = "15236547789"; log.info(phone); Log.info (" test log phone: {}", phone); Log.info (" Test log JSON object: {}", jsonObject.tojsonString (params)); }} ------------------ The following information is displayed: 15236547789 Test log Phone number: 15236547789 Test log JSON object: {" Phones ":" 13668200646152222222156852699 ", "id" : "150303195208077885150031520071 X 58, 15030319520807908 X", "timest Amp ":" 1231 ", "NAME" : "* *"}Copy the code
Desensitization operation
-
It can be found that the printed log has also printed out the complete mobile phone number. If there is some sensitive customer information, such as ID card, mobile phone number, bank card and so on, it is necessary to desensitize.
-
Especially if the online log is connected to a third-party log system (such as Ali Cloud SLS log service), some user data information will be directly printed out without log desensitization, resulting in data leakage and a series of problems
-
First you need to custom implementation desensitization SensitiveLogDataConverter and inherit MessageConverter class news, a log message provided by the logback superclass. The code is as follows:
/** * Custom log desensitization ** @author: ZRH * @date: 2021/9/27 returned to * / public final class SensitiveLogDataConverter extends MessageConverter {/ * * * * bank card and name the regular match type/private The static Pattern bankCardPattern = Pattern.com running (" (\ D) ([3-6] \ D {3}) (\ D {8, 12}) (\ D {4}) (\ D) "); private static Pattern namePattern = Running the Pattern.com (" ([^ \ u4e00 - \ u9fa5]) ([\ u4e00 - \ u9fa5]) ([\ u4e00 - \ u9fa5] {1, 3}) ([^ \ u4e00 - \ u9fa5]) "); /** * private final static Pattern PHONE_PATTERN = pattern.compile ("(?<! \d)(1\d{10})(? ! \d)"); private final static Pattern ID_CARD_PATTERN = Pattern.compile("(?<! \ d) (\ d {6}) (19, 20] [\ d {7}) (\ d {3} [xx] 0-9) (? ! \d)"); @Override public String convert (ILoggingEvent event) { try { final Set<String> list; String logMsg = event.getFormattedMessage(); if (! (list = validateIdCard(logMsg)).isEmpty()) { for (String param : list) { logMsg = logMsg.replaceAll(param, SensitiveInfoUtil.desensitizePhoneOrIdCard(param)); } } return logMsg; } catch (Exception e) { } return super.convert(event); ** @param param * @return */ private static Set<String> validateIdCard (String param) { Set<String> set = new HashSet<>(); Matcher phoneMatcher = phone_pattern.matcher (param); while (phoneMatcher.find()) { set.add(phoneMatcher.group()); } // match idCardMatcher idCardMatcher = id_card_pattern.matcher (param); while (idCardMatcher.find()) { set.add(idCardMatcher.group()); } return set; }}Copy the code
- You also need to configure a custom log print format file logback.xml
<? The XML version = "1.0" encoding = "utf-8"? > <configuration debug="true" scan="true" scanPeriod="1 seconds"> <contextName>logback</contextName> <property name="log.path" value="logs/yx-api-admin.log"/> <! - specify the location of the desensitization class - > < conversionRule conversionWord = "MSG" converterClass = "com. Work. Web. Log. SensitiveLogDataConverter" / > <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern> <charset>UTF-8</charset> </encoder> </appender> <appender name="info" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${log.path}</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${log.path}.%d{yyyy-MM-dd}.zip</fileNamePattern> </rollingPolicy> <encoder> <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n </pattern> <charset>UTF-8</charset> </encoder> </appender> <root level="info"> <appender-ref ref="console"/> <appender-ref ref="info"/> </root> </configuration>Copy the code
- Again, see the final result:
/** * @Author: ZRH * @Date: 2021/9/27 17:25 */ @Slf4j public class TestLog { //public static final Logger log = LoggerFactory.getLogger(TestLog.class); public static void main (String[] args) { Map<String, String> params = new HashMap<>(); Params. Put (" Phones ", "13668200646152222222156852699"); params.put("timestamp", "1231"); Params. Put ("NAME", "zhang SAN "); Params. Put (" id ", "150303195208077885150031520071 X 58, 15030319520807908 X"); String phone = "15236547789"; log.info(phone); Log.info (" test log phone: {}", phone); Log.info (" Test log JSON object: {}", jsonObject.tojsonString (params)); }} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- to print the results are as follows: 152 * * * * 7789 test log tel: 152 * * * * 7789 test log json object: {" Phones ":" * * * * 0646152 * 136 * 2222156 * * * * * * 3699 ", "id" : "150 * * * * * * * * * * * 7885150 * * * * * * * * * * * 158 x, 150 * * * * * * * * * * * 908 x", "timest Amp ":" 1231 ", "NAME" : "* *"}Copy the code
The last
- Learn with an open mind and make progress together