Removing sensitive information from logs in ASP.NET Core logging
Asked Answered
H

2

16

I am using ASP.NET Core logging abstraction for my application.

I have a list of sensitive strings that i would like to make sure is masked "*****" in the logs when sent to any sinks. (I am using serilog - but maybe it can be plugged in even before serilog).

How would I plug this into the ASP.NET Core logging system to replace all these sensitive strings with "*******" before sent to any sinks / writers etc.

Humoral answered 12/2, 2018 at 18:58 Comment(0)
M
17

Without knowing what you are trying to scrub, there are a few options.

There are several good ideas in this GitHub issue.

To summarize the thread: You can use an enricher to completely wipe the contents of a property. You could also use a text formatter to manually run regex replacements.

There are also a few packages mentioned that you can add to provide more structure around processing your log:

Mcsweeney answered 12/2, 2018 at 21:21 Comment(0)
F
1

I was having a similar problem where I would need to redact/hide certain fields from an object during logging.

For brevity let's assume object is

public class User
{
   public string UserName { get; set; }
   public string Password { get; set; }
   public override string ToString()
   {  
       return base.ToString();
   }
}

Now we log with serilog using the object destructure operator(@)

User user = new User() { UserName = "u", Password = "p" };
_logger.LogWarning("value is {@val}", user);

In order to hide the Password prop we can setup serilog as below

Log.Logger = new LoggerConfiguration()
                        .WriteTo.Console(new Serilog.Formatting.Json.JsonFormatter())
                        .Destructure.ByTransforming<User>(_ => new { User = _.UserName })
                        .CreateLogger();

Now for any logging of object User won't have Password field in it or you can redact Password field by setting Password = "######"

P.S. Ideally we should not log anything sensitive but at times we need to log the whole object where certain props are not desirable to be logged and above is a centralized approach to handle such scenario rather than reviewing every commit in code to verify this potential mistake.

Forborne answered 13/11, 2021 at 12:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.