How do I mask sensitive data using standard log in Go?

To mask sensitive data in Go while logging, you can create a custom logger that replaces sensitive information with a placeholder before sending the logs to the output. This practice helps ensure that sensitive data like passwords, API keys, or personal information is not exposed in your logs.

Here's an example of how you can achieve this in Go:

package main import ( "log" "os" "regexp" ) // maskSensitiveData masks the sensitive information in the log message. func maskSensitiveData(message string) string { // Example regex to match email addresses. You can enhance this for other sensitive data. emailRegex := regexp.MustCompile(`([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})`) maskedMessage := emailRegex.ReplaceAllString(message, "[MASKED_EMAIL]") return maskedMessage } func main() { // Create a log file file, err := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err != nil { log.Fatal(err) } defer file.Close() // Set the log output to the file log.SetOutput(file) // Log a message with sensitive data sensitiveMessage := "User login attempt: user@example.com" log.Println(maskSensitiveData(sensitiveMessage)) }

Go sensitive data log masking custom logger security