Avoid direct System.debug statements

Helper class to conditionally call System.debug

  • This pattern uses helper class to have a single place which calls System.debug
    • All other Apex classes should call helper class instead of System.debug to improve production org performance
    • Easiest way is to find and replace System.debug with LogHelper.debug across the whole org codebase
  • Helper class checks if the user have custom permission SystemDebugStatementsEnabled set either via profile or permission set with the built-in FeatureManagement class
  • System.debug is called by default when running the tests
    • Optionally one could mark static variable debugStatementsEnabled as @TestVisible so that certain test class will activate debugging when needed
public class LogHelper {
	private static Boolean debugStatementsEnabled = FeatureManagement.checkPermission('SystemDebugStatementsEnabled');
	public static void log(System.LoggingLevel level, Object data) {
		if (debugStatementsEnabled || Test.isRunningTest()) {
			System.debug(level, data);
		}
	}
	public static void debug(Object data) {
		log(LoggingLevel.DEBUG, data);
	}
}

Post originally written by Leo Jokinen (Fluido)

Leave a comment