1

I want to enhance my logger with a compile-time safety check that prevents me from logging personally-identifying or sensitive data. Here's what I imagine the interface could look like:

logger.LogInfo(safeuser => $"Logging out sensitive data @{safeuser.lastname}", user);
// Error: SafeToLog<User> does not contain a definition for 'lastname'

This line should not compile.

The regular User class has properties id, firstname, lastname, createdAt, roleId, password etc. Some of those fields are perfectly fine to log, like id and roleId. The ones that are unsafe to log will be marked with attributes like [PersonallyIdentifying] or [Secret].

I want a type like SafeToLog<T> that has methods for every safe-to-log property of T, but no methods for the unsafe-to-log properties. So SafeToLog<User> should have properties id, createdAt, and roleId. It should NOT have properties firstname, lastname or password.

Is it possible to implement the SafeToLog type? In Typescript I could use the Omit helper type to construct this, but I don't know how to do it in C#.


Furthermore, would it be possible to prevent accidental misuse of the logger? In the sample above, a careless developer could still refer to user in the log string, ignoring safeuser and bypassing the safety check. Can I somehow enforce that only the variables provided in the lambda are referenced in the log message?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Devon Parsons
  • 1,234
  • 14
  • 23
  • Did you have any luck with this? If so please post an answer, I've seen this https://stackoverflow.com/q/33148957/495455 but am hoping there is something in-built. – Jeremy Thompson Dec 15 '22 at 04:57

0 Answers0