Swift – Hide sensitive information when showing log

Tram Ho

We’ve all gotten used to debugging by printing out the data information to the console so that we can easily investigate the problem. If our app involves payment transactions or the information needs to be secure, but we still need to log it for tracking, for statistics of user habits or for bug fixes. In this article, we will hide sensitive information when logging out.

Initially

Basically, in my project, I will have a struct model as follows:

And normally, when debugging, we will use the following func to print out information about the object including its values. For example, I will create a user as follows:

After that, I will print out that user using print (….)

The output will now be:

For example, we want to hide the user’s email and dateOfBirth information when sending the log to the server or printing the log to the console, but for now, the data is still exposed, which can cause risks in project. For example, we use Sentry to send log up for statistics and tracking data, we will use a func as follows:

We can use the following:

Let’s take a look at the log below:

At this point, all user data is logged, although one of them is not strictly necessary in the case of tracking. So how can we hide the user’s information without needing or wanting to debug, log out?

Solution

Since version swift 5.1, we have added a name that is: Property Wrappers. You can read more here By using Property Wrappers, we will add an extra layer to hide information that we do not want it to be saved, debugged … Below will be the paragraph The code we need to add in the project:

The above code does not handle anything too complicated, it simply helps to ensure that whenever we try to use the print function, debugPrint, dump the data of that object, it is hidden. its value is “hidden” instead.

Next, for whatever properties we want to hide, we will prepend the LoggingExcluded prefix. For example, I will hide city and email, this time the model will edit as follows:

Let’s try to print it out together

The result now:

Conclusion

The above is an idea to hide information after learning and reading about Property Wrapper, hope it will be useful to you. Thank you.

Share the news now

Source : Viblo